简体   繁体   English

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

[英]How do I reduce the quality of an image in byte format on Android?

Using resources from StackOverflow and other helpful websites, I was successful in creating an application that can upload an image taken by the camera application on an Android phone. 利用StackOverflow和其他有用网站的资源,我成功创建了一个应用程序,可以将相机应用程序拍摄的图像上传到Android手机上。 The only trouble is, the phone I have right now takes very high-quality pictures, resulting in a long wait-time for uploads. 唯一的麻烦是,我现在拥有的电话会拍摄非常高质量的照片,导致上传时间较长。

I read about converting images from jpeg to a lower rate (smaller size or just web-friendly sizes), but the code I am using right now saves the captured image as a byte (see code below). 我读过有关将图像从jpeg转换为较低速率(较小的尺寸或仅为Web友好的尺寸)的信息,但是我现在使用的代码现在将捕获的图像保存为字节(请参见下面的代码)。 Is there any way to reduce the quality of the image in the form that it is in, or do I need to find a way to convert it back to jpeg, reduce the image quality, and then place it back in byte form? 有什么方法可以降低图像的质量,还是我需要找到一种方法可以将其转换回jpeg,降低图像质量,然后再以字节格式放置?

Here is the code snippet I'm working with: 这是我正在使用的代码片段:

    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());
            }
        }
    }
}

For web apps, you definitely don't need the 5+ MP images that cameras produce; 对于Web应用程序,您绝对不需要相机生成的5+ MP图像。 image resolution is the primary factor in image size, so I'd suggest you use the BitmapFactory class to produce a downsampled bitmap. 图像分辨率是图像大小的主要因素,因此建议您使用BitmapFactory类来生成降采样的位图。

Particularly, look at BitmapFactory.decodeByteArray(), and pass it a BitmapFactory.Options parameter indicating you want a downsampled bitmap. 特别是,请查看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);

For more info, take a look at the Android Training lesson on displaying bitmaps efficiently and the reference for BitmapFactory: 有关更多信息,请查看有关有效显示位图的Android培训课程以及BitmapFactory的参考:

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

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

To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. 要告诉解码器对图像进行二次采样,将较小的版本加载到内存中,请在BitmapFactory.Options对象中将inSampleSize设置为true。 For example, an image with resolution 2048x1536 that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. 例如,使用inSampleSize为4解码的分辨率为2048x1536的图像会生成大约512x384的位图。 Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888). 将其加载到内存中需要使用0.75MB而不是12MB的完整图像(假设ARGB_8888的位图配置)。 see this 看到这个

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html 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;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM