[英]Android, Compressing an image
我通過網絡通過wifi或移動網絡發送圖像以存儲在服務器中並再次檢索。 我已經做到了,但是由於相機拍攝的圖像大小,它使我的應用程序變慢,只是指出我打開畫廊並從那里拍攝照片而不是直接從應用程序拍攝照片。 我注意到從相機和畫廊拍攝的whatsapp圖像已被壓縮到大約。 100KB。
目前,我的代碼獲取一個文件並將其轉換為字節,然后發送它。 這是獲取文件並將其轉換為字節的方法。
private void toBytes(String filePath){
try{
File file = new File(filePath);
InputStream is = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
bytes = new byte[(int) filePath.length()];
int bytes_read;
while((bytes_read = is.read(bytes, 0, bytes.length)) != -1){
buffer.write(bytes, 0, bytes_read);
}
is.close();
bytes = buffer.toByteArray();
}catch(Exception err){
Toast.makeText(getApplicationContext(), err.toString(), Toast.LENGTH_SHORT).show();
}
}
所以我的問題是如何在發送之前壓縮我的圖像? 此外,我不需要圖像保留高像素數,因為當應用程序使用圖像時,它將只占用設備屏幕的一半。
謝謝你給予的任何幫助。
BitMap
http://developer.android.com/reference/android/graphics/Bitmap.html類有一個compress
方法。 但是您可能需要縮放圖像createScaledBitmap
,也可以在同一個類中使用。
嘗試使用以下方法:
//decodes image and scales it to reduce memory consumption
//NOTE: if the image has dimensions which exceed int width and int height
//its dimensions will be altered.
private Bitmap decodeToLowResImage(byte [] b, int width, int height) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o);
//The new size we want to scale to
final int REQUIRED_SIZE_WIDTH=(int)(width*0.7);
final int REQUIRED_SIZE_HEIGHT=(int)(height*0.7);
//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_WIDTH || height_tmp/2<REQUIRED_SIZE_HEIGHT)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o2);
} catch (OutOfMemoryError e) {
}
return null;
}
名為SiliCompressor的Android庫已經過優化,可以為您完成所有圖像壓縮。 在Github上查看
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.