1

I'm setting an ImageView to a file downloaded from a remote server then saved to the device's local storage. For some reason, the image is getting distorted. From my research, if I set the scaleType, adjustViewBounds, maxWidth and maxHeight properties of the ImageView, then Android will scale the image for me. That seems strange because in my other, non-Android developing, I've always had to resize the image programmatically first before displaying it. However, this post says Android will do it.

This is the image I'm trying to display: Image

Distorted image:

enter image description here

Code:

    <ImageView
        android:id="@+id/title_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxWidth="60dp"
        android:maxHeight="60dp"
        android:scaleType="fitCenter"
        android:adjustViewBounds="true"
        />

    String path =  getExternalStorageDirectory() + "/MyApp/Images";
    String fileName = "Test.jpg";
    File imageFile = new File(path, fileName);

    if (imageFile.exists())
    {
        Uri imageUri = Uri.fromFile(imageFile);
        ((ImageView)findViewById(R.id.title_image)).setImageURI(thumbnail);
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kris B
  • 3,436
  • 9
  • 64
  • 106

1 Answers1

0

If it helps anyone, I ended up resizing the image with code using this:

            final URLConnection ucon = new URL(url).openConnection();
            final InputStream is = ucon.getInputStream();
            final Bitmap b = BitmapFactory.decodeStream(is);

            int origWidth = b.getWidth();
            int origHeight = b.getHeight();
            float scaleWidth = ((float) width) / origWidth;
            float scaleHeight = ((float) width) / origHeight;

            final Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);

            Bitmap b2 = Bitmap.createBitmap(b, 0, 0, origWidth, origHeight, matrix, false);

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            b2.compress(Bitmap.CompressFormat.PNG, 100, outStream);

            FileOutputStream fo = new FileOutputStream(file);
            fo.write(outStream.toByteArray());
            fo.flush();
            fo.close();
            outStream.flush();
            outStream.close();
            b.recycle();
            b2.recycle();
Kris B
  • 3,436
  • 9
  • 64
  • 106