如何在Android上以字节格式降低图像质量?

时间:2012-12-10 21:19:39

标签: android image upload compression

使用来自StackOverflow和其他有用网站的资源,我成功地创建了一个可以在Android手机上传相机应用程序拍摄的图像的应用程序。唯一的麻烦是,我现在拥有的手机拍摄的照片质量非常高,导致上传的等待时间很长。

我读到了将图像从jpeg转换为较低的速率(较小的尺寸或只是网络友好的尺寸),但我现在使用的代码将捕获的图像保存为一个字节(参见下面的代码)。有没有办法以它所处的形式降低图像的质量,或者我是否需要找到一种方法将其转换回jpeg,降低图像质量,然后将其放回字节形式?

以下是我正在使用的代码段:

    if (Intent.ACTION_SEND.equals(action)) {

        if (extras.containsKey(Intent.EXTRA_STREAM)) {
            try {

                // Get resource path from intent callee
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);

                // Query gallery for camera picture via
                // Android ContentResolver interface
                ContentResolver cr = getContentResolver();
                InputStream is = cr.openInputStream(uri);
                // Get binary bytes for encode
                byte[] data = getBytesFromFile(is);

                // base 64 encode for text transmission (HTTP)
                int flags = 1;
                byte[] encoded_data = Base64.encode(data, flags);
                // byte[] encoded_data = Base64.encodeBase64(data);
                String image_str = new String(encoded_data); // convert to
                                                                // string

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("image",
                        image_str));

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://xxxxx.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String the_string_response = convertResponseToString(response);
                Toast.makeText(UploadImage.this,
                        "Response " + the_string_response,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                System.out.println("Error in http connection "
                        + e.toString());
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

对于网络应用,你绝对不需要相机产生的5+ MP图像;图像分辨率是图像大小的主要因素,因此我建议您使用BitmapFactory类生成下采样位图。

特别是,看看BitmapFactory.decodeByteArray(),并传递一个BitmapFactory.Options参数,表明你想要一个缩减采样的位图。

// your bitmap data
byte[] rawBytes = .......... ;

// downsample factor
options.inSampleSize = 4;  // downsample factor (16 pixels -> 1 pixel)

// Decode bitmap with inSampleSize set
return BitmapFactory.decodeByteArray(rawBytes, 0, rawBytes.length, options);

有关详细信息,请查看有关显示位图的Android培训课程以及BitmapFactory的参考:

http://developer.android.com/training/displaying-bitmaps/index.html

http://developer.android.com/reference/android/graphics/BitmapFactory.html

答案 1 :(得分:2)

告诉解码器对图像进行二次采样,将较小的版本加载到内存中,在BitmapFactory.Options对象中将inSampleSize设置为true。例如,使用inSampleSize为4解码的分辨率为2048x1536的图像会产生大约512x384的位图。将其加载到内存中对于完整图像使用0.75MB而不是12MB(假设ARGB_8888的位图配置)。看到这个

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

public   Bitmap decodeSampledBitmapFromResource(
  String pathName) {
int reqWidth,reqHeight;
reqWidth =Utils.getScreenWidth();
reqWidth = (reqWidth/5)*2;
reqHeight = reqWidth;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//  BitmapFactory.decodeStream(is, null, options);
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}

   public   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) {
  if (width > height) {
    inSampleSize = Math.round((float) height / (float) reqHeight);
  } else {
    inSampleSize = Math.round((float) width / (float) reqWidth);
  }
}
return inSampleSize;
 }