views:

1503

answers:

4

I want to show images using drawBitmap() method. But before I want to resize it according screen dimensions. I have a problem with quality of result image. You can see screenshots and test code below. How can I resize images in runtime with a good quality?

Thank you for solutions.

Original image: alt text

Result screenshot on device: alt text

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import java.io.IOException;
import java.io.InputStream;

public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout container = (LinearLayout) findViewById(R.id.container);
        container.addView(new View(this) {
            @Override
            protected void onDraw(Canvas canvas) {
                Bitmap unscaledBitmap;
                try {
                    InputStream in = getAssets().open("images/gradient.png");
                    unscaledBitmap = BitmapFactory.decodeStream(in);
                    in.close();
                    canvas.drawBitmap(unscaledBitmap, null, new Rect(0, 0, 320, 480), null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
+1  A: 

Check out http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html (To be used with unscaledBitmap = BitmapFactory.decodeStream(in);

You can add quality settings to the image. I'm guessing that the quality is being degraded as you are not passing any settings for how the image should be processed.

steve
A: 

Also, if your resizing function does not respect the aspect ratio of the image, the quality gets affected. You can find some resizing algorithm on the web, for instance check this out

Samuh
No, the both images have the same ratio.original image: 600x900 ratio 1.5new image size: 320x480 ratio 1.5
Roces
+2  A: 

Note that Android can only do 16-bit colour, so there may be times when you get unwanted artifacts.

You can also try using the dither options to tell Android to automatically apply dithering which, while not perfect, can help make things look a bit better.

Christopher
Thank you, it's helpful answer! But I have no reputation to vote it.
Roces
Now I'm using the "565 dither photoshop plugin" to prepare my graphic. Because dithering is hi-cost operation and it doesn't work with decodeStream and drawBitmap methods.
Roces
+2  A: 

Instead of resizing at drawing time (which is going to be very costly), try to resize in an offscreen bitmap and make sure that Bitmap is 32 bits (ARGB888).

Romain Guy