1. 程式人生 > >android實現一張或多張圖片壓縮並保持清晰上傳

android實現一張或多張圖片壓縮並保持清晰上傳

圖片過大,大於1M的情況下上傳伺服器會很耗時,因此要實現壓縮上傳並且不失真

String mCurrentPhotoPath;
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// 指定存放拍攝照片的位置
File f = createImageFile();
openCameraIntent
        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(openCameraIntent, REQUEST_TAKE_PHOTO
);

private File createImageFile()  {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String timeStamp = format.format(new Date());
    String imageFileName = "pic_" + timeStamp + ".jpg";
    File appDir = new File(Environment.getExternalStorageDirectory(), "qx");
    if 
(!appDir.exists()) { appDir.mkdir(); } File image = new File(appDir, imageFileName); mCurrentPhotoPath = image.getAbsolutePath(); return image; }
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {case  REQUEST_TAKE_PHOTO
: if (resultCode == Activity.RESULT_OK) { // 新增到相簿,通知更新 galleryAddPic(this, mCurrentPhotoPath); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); cardIv.setImageBitmap( getSmallBitmap(mCurrentPhotoPath)); } break; } }
public static Bitmap getSmallBitmap(String filePath) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
    // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(filePath, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
                                        int reqWidth, int reqHeight) {
    // Raw height and width of image
final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

public static void galleryAddPic(Context context, String path) {
    Intent mediaScanIntent = new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(path);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}
在上傳至伺服器時進行再次壓縮防止一個或多個檔案有點大時上傳慢或者不清晰

如果顯示類似於頭像,朋友圈顯示的小圖片等實現壓縮到幾十k以下上傳,如果展示圖片大一點並且後臺檢視保持清晰時可實現壓縮到幾百k以下上傳

map.put(KeyConstants.Image, getcomImageBase64(getSmallBitmap(mCurrentPhotoPath)));
//壓縮成100k以下上傳
public static String getcomImageBase64(Bitmap bitmap) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 100是壓縮率不壓縮,如果是30就是壓縮70%,壓縮後的存放在baos中
int options = 100;
    while (baos.toByteArray().length / 1024 > 100) { // 迴圈判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
baos.reset();// 重置baos即清空baos
options -= 10;// 每次都減少10
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裡壓縮options%,把壓縮後的資料存放到baos中
}
    byte[] bytes = baos.toByteArray();
    try {
        baos.flush();
        baos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
e.printStackTrace();
    }
    return Base64.encodeToString(bytes, Base64.DEFAULT);

}


原文地址:http://www.360doc.com/content/14/0428/17/11800748_372972179.shtml