Zoom Image By Path - Android Media

Android examples for Media:Picture

Description

Zoom Image By Path

Demo Code


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Rect;
import android.media.ThumbnailUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main{
    public static Bitmap ZoomImageByPath(String pathName, int outputWidth,
            int outputHeight) {
        Bitmap bitmap = null;//from  w w  w. j  av a 2s.  c o  m
        Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, opts);

        opts.inJustDecodeBounds = false;
        float scale = getOptimalScale(opts.outWidth, opts.outHeight,
                outputWidth, outputHeight);

        if (scale <= 0) {
            throw new NullPointerException("ImageZoomUtil: scale = "
                    + scale + "<=0");
        } else if (scale > 1) {
            opts.inSampleSize = (int) scale;
            bitmap = BitmapFactory.decodeFile(pathName, opts);
            return EnhancedExtractThumbnail(bitmap, outputWidth,
                    outputHeight);
        } else {
            return BitmapFactory.decodeFile(pathName, opts);
        }
    }
    
    private static float getOptimalScale(int sourceWidth, int sourceHeight,
            int templateWidth, int templateHeight) {
        LogUtils.d("originWidht : " + sourceWidth + "originHeight : "
                + sourceHeight + "toWidht : " + templateWidth
                + "toWidht : " + templateHeight);
        float scale = 1;
        float scaleX = sourceWidth / (float) templateWidth;
        float scaleY = sourceHeight / (float) templateHeight;
        if (scaleX > scaleY && scaleY > 0) {
            scale = scaleX;
        } else if (scaleX < scaleY && scaleX > 0) {
            scale = scaleY;
        }
        return scale;
    }
    
    private static Bitmap EnhancedExtractThumbnail(Bitmap bitmap,
            int outputWidth, int outputHeight) {
        int curWidth = bitmap.getWidth();
        int curHeight = bitmap.getHeight();
        float scale = getOptimalScale(curWidth, curHeight, outputWidth,
                outputHeight);
        outputWidth = (int) (curWidth / scale);
        outputHeight = (int) (curHeight / scale);
        return ThumbnailUtils.extractThumbnail(bitmap, outputWidth,
                outputHeight);

    }
}

Related Tutorials