Image crop and resize in Android

后端 未结 8 966
无人及你
无人及你 2020-12-19 15:58

I followed the instructions below to crop an image.

http://coderzheaven.com/index.php/2011/03/crop-an-image-in-android/

The height and width of the final cro

相关标签:
8条回答
  • 2020-12-19 16:32

    04-09 11:37:28.708: ERROR/AndroidRuntime(4003): at com.test.Test.onCreate(Test.java:57)

    If I'm not mistaken, in

    class Test extends Activity ....
    

    on line 57, you have

    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image);
    

    If so, the referenced image is so big that when Android tries to decode it into a bitmap, it cosumes all the free VM heap and throws theerror. You cant decode big bitmaps with

    private Bitmap decodeFile(){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getResources(),R.drawable.image,o);
    
            //The new size we want to scale to
            final int REQUIRED_SIZE=100;
    
            //Find the correct scale value. It should be the power of 2.
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
    
            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeResource(getResources(),R.drawable.image, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
    

    I copied the code from the link that user699618 recommended, i ve used it before and it solves the problem).

    After that you can just use CENTER_CROP or whatever you need on ImageView.setScaleType().

    You can find the Scale Type options in here and setScaleType details in hete.

    Hope this helps.

    i'd also recommend not to have such heavy pictures in resources. Make them smaller before saving them in the resorce forder.

    0 讨论(0)
  • 2020-12-19 16:37

    My co-worker just hipped me to this Android API... see ThumbnailUtils.

    It does resizing and cropping for you.

    http://developer.android.com/reference/android/media/ThumbnailUtils.html#extractThumbnail(android.graphics.Bitmap, int, int)

    0 讨论(0)
提交回复
热议问题