2013-11-04 107 views
0

我试图缩放图片,它起初运行良好,但是当缩小很多时它似乎不起作用。一段时间后,它停止缩小。我无法获得质量为0的小于630的字节数。我意识到这是一个垃圾图片,但我想要将其缩小很多,它根本不起作用。任何想法将不胜感激。Android位图不会缩放

ByteArrayOutputStream out; 
    Bitmap bitmap = BitmapFactory.decodeStream(in); 
    int width = bitmap.getWidth(); //3920 
    int height = bitmap.getHeight(); //2204 

    float scale = 0.0034; //usually calculated in runtime but set for simplicity now. 

    // Resize the bitmap 
    Matrix matrix = new Matrix(); 
    matrix.postScale(scale, scale); 

    // Recreate the new bitmap 
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); 

    out = new ByteArrayOutputStream(); 
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 0, out); 

    return out.toByteArray(); 

回答

0

可以使用矩形重新缩放的位图

Rect srcrect = new Rect(0,0,yourbitmap.getWidth(),yourbitmap.getHeight()); 
Rect destrect = new Rect(startindexxright,startindexyright,startindexxleft,startindexyleft); 
canvas.drawBitmap(yourbitmap, srcrect,destrect, null); 

srcrect是,你必须您的位图和destrect的输入的细节的矩形是在设备显示器(的部分的面积在其中想要显示图像)。

+0

谢谢,但我需要缩小它,因为我需要通过网络发送它,并且我有严格的大小限制。我可以使用矩形来缩放它,然后从中获取一个字节数组吗? –

0

检查BitmapFactory.Options.InSampleSize

此代码减少存储在文件中的位图,但它应该很容易适应代码到一个内存位图

public static Bitmap getReducedBitmap(Context context, String path) {  
    File bitmapFile = new File(path); 

    Uri uri = Uri.fromFile(bitmapFile); 
    InputStream in = null; 

    ContentResolver contentResolver = context.getContentResolver(); 

    try { 
     in = contentResolver.openInputStream(uri); 

     // Decode image size 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(in, null, options); 
     in.close(); 

     //scale works better with powers of 2 
     int scale = 1; 
     while ((options.outWidth * options.outHeight) * (1/Math.pow(scale, 2)) > WSConfig.PICTURE_MAX_PIXELS) { 
     scale++; 
     } 

     Bitmap reducedBitmap = null; 
     in = contentResolver.openInputStream(uri); 
     if (scale > 1) { 
     // scale to max possible inSampleSize that still yields an image 
     // larger than target 
     options = new BitmapFactory.Options(); 
     options.inSampleSize = scale; 
     reducedBitmap = BitmapFactory.decodeStream(in, null, options);  
     } else { 
     reducedBitmap = BitmapFactory.decodeStream(in); 
     } 
     in.close(); 

     return reducedBitmap; 
    } catch (IOException e) { 
     Log.e("UTILS", e.getMessage(), e); 
     return null; 
    } 
    } 

我MAX_PICTURE_PICTURES决定了最大分辨率