1

我正在制作一个相机应用程序。而且我必须在相机点击到服务器后保存图像,因为捕获的图像的大小总是非常大(以 Mb 为单位)。所以我总是很难将大尺寸的图像保存在服务器上。保存之前有没有压缩图像的。?

而且我只能使用android原生相机

谢谢

4

3 回答 3

2

在将位图实际上传到服务器之前,您需要调整其大小。此代码返回调整大小的位图。将位图减小到所需的宽度和高度 - 这将导致图像文件更小。

public static Bitmap getBitmapImages(final String imagePath, final int requiredWidth, final int requiredHeight)
{
    System.out.println(" --- image_path in getBitmapForCameraImages --- "+imagePath+" - reqWidth & reqHeight "+requiredWidth+" "+requiredHeight);
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = true;
    options.inJustDecodeBounds = true;

    // First decode with inJustDecodeBounds=true to check dimensions
    bitmap = BitmapFactory.decodeFile(imagePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);

    options.inJustDecodeBounds = false;

    // Decode bitmap with inSampleSize set
    bitmap = BitmapFactory.decodeFile(imagePath, options);

    return bitmap;
}
于 2012-10-08T11:49:46.430 回答
1

另一种方法是直接制作较小的图片。这样做的好处是您使用的内存更少,但您可能需要在应用程序的另一部分有大图景。

这可以按如下方式完成:

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
...
   Camera.Parameters mParameters = mCamera.getParameters();
   List<Size> sizes = mParameters.getSupportedPictureSizes();
   Size optimalSize = getOptimalSize(sizes, width, height);
   if (optimalSize != null && !mParameters.getPictureSize().equals(optimalSize))
        mParameters.setPictureSize(optimalSize.width, optimalSize.height);
...
}  

要选择最佳尺寸,您可以使用任何您想要的标准。我试图使其尽可能接近屏幕尺寸:

 private Size getOptimalSize(List<Size> sizes, int w, int h){

    final double ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w / h;
    if (sizes == null)
        return null;

    Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Size size: sizes)
    {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
            continue;
        if (Math.abs(size.height - targetHeight) < minDiff)
        {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null)
    {
        minDiff = Double.MAX_VALUE;
        for (Size size: sizes)
        {
            if (Math.abs(size.height - targetHeight) < minDiff)
            {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }

    return optimalSize;

}
于 2012-10-08T12:01:40.967 回答
0

尝试这个

            Bitmap bmp = (Bitmap) data.getExtras().get("data");

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
于 2012-10-08T11:53:28.670 回答