2012-11-24 146 views
1

我有一個Java應用程序允許用戶從他的相機拍照並使用Web服務將其發送給我,但是我的問題是在發送圖像時。發送過程需要很長時間,因爲圖像很大,所以我想壓縮圖像。我曾嘗試:在java中調整圖像大小

1-使用此代碼:

Bitmap img = BitmapFactory.decodeFile("C:\\test.jpg"); 

ByteArrayOutputStream streem = new ByteArrayOutputStream(); 
img.compress(Bitmap.CompressFormat.JPEG, 75, streem); 
byte[] b = streem.toByteArray(); 

但是這個代碼是在我的情況下,無用的,因爲它使圖像非常糟糕,dosent圖像大小影響了很多。

2-搜索了很多關於調整方式的方法,但所有結果都使用了BufferedImage。因爲它需要大量的內存大小的我不能使用此類型(類):

private static BufferedImage resizeImage(BufferedImage originalImage, int type) 
{ 
    BufferedImage resizedImage = new BufferedImage(new_w, new_h, type); 
    Graphics2D g = resizedImage.createGraphics(); 
    g.drawImage(originalImage, 0, 0, new_w, new_h, null); 
    g.dispose(); 

    return resizedImage; 
} 

我想使用位圖代替,任何機構可以幫助我在我的應用程序???

+1

嘗試使用JPEG壓縮的一個更高的水平。查看[這個答案](http://stackoverflow.com/questions/5995798/java-text-on-image/5998015#5998015)供代碼試驗。 –

回答

1

我發現這些拖方法:

private static int CalculateInSampleSize(BitmapFactory.Options options, 
     int reqWidth, int reqHeight) { 
    float height = (float) options.outHeight; 
    float width = (float) options.outWidth; 
    float inSampleSize = 0; 

    if (height > reqHeight || width > reqWidth) { 
     inSampleSize = width > height ? height/reqHeight : width 
       /reqWidth; 
    } 

    return (int) Math.round(inSampleSize); 
} 

public static byte[] ResizeImage(int reqWidth, int reqHeight, byte[] buffer) { 
    BitmapFactory.Options op = new Options(); 
    op.inJustDecodeBounds = true; 

    BitmapFactory.decodeByteArray(buffer, 0, buffer.length, op); 

    op.inSampleSize = CalculateInSampleSize(op, reqWidth, reqHeight); 

    op.inJustDecodeBounds = false; 
    try { 
     return ToByte(BitmapFactory.decodeByteArray(buffer, 0, 
       buffer.length, op)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 

}