android圖片壓縮
andriod提供了一些方法如下:壓縮圖片質量:
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
其中的quality為0~100, 可以壓縮圖片質量, 不過對於大圖必須對圖片resize
這個是等比例縮放:
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
這個是截取圖片某部分:
bitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
這段代碼很多網站都有轉載,在這裏是為了注釋:較大的圖片文件上傳到服務器一般都需要壓縮調整,保證數據通信的效率是最主要的。
//對圖片進行壓縮
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//獲取這個圖片的寬和高
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);//此時返回bm為空
options.inJustDecodeBounds =false;
//計算縮放比
int be = (int)(options.outHeight / (float)200);
if(be <= 0)
be =1;
options.inSampleSize =be;
//重新讀入圖片,注意這次要把options.inJustDecodeBounds設為false哦
bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);
int w = bitmap.getWidth();
int h=bitmap.getHeight();
System.out.println(w+" "+h);
myImageView.setImageBitmap(bitmap);
//保存入sdCard
File file2= new File("/sdcard/dcim/Camera/test.jpg");
try {
FileOutputStream out = new FileOutputStream(file2);
if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){
out.flush();
out.close();
}
} catch (Exception e) {
// TODO: handle exception
}
//讀取sd卡
File file =new File("/sdcard/dcim/Camera/test.jpg");
int maxBufferSize = 16 * 1024;
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
BufferedInputStream bufferedInputStream;
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int bytesAvailable = bufferedInputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
while ((len = bufferedInputStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, bufferSize);
}
data = outStream.toByteArray();
outStream.close();
bufferedInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
最後更新:2017-04-02 16:47:34