2013-11-04 105 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決定了最大分辨率