如何在上传到服务器之前减小图像文件大小

时间:2013-09-02 12:51:29

标签: android image upload

许多应用程序允许共享从图库中挑选的图像。

他们上传原始图片文件了吗?这是1-3 MB?或者他们处理?

在任何情况下,我如何从文件路径中获取图像,通过降低分辨率来减小其大小,并将其保存在其他地方并尝试上传?

我试过了:

Bitmap photo = decodeSampledBitmapFromFile(filePath, DESIRED_WIDTH,
                    DESIRED_HEIGHT);

FileOutputStream out = new FileOutputStream(filePath);
photo.compress(Bitmap.CompressFormat.JPEG, 100, out);

public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth,
        int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    final int height = options.outHeight;
    final int width = options.outWidth;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    int inSampleSize = 1;

    if (height > reqHeight) {
        inSampleSize = Math.round((float) height / (float) reqHeight);
    }
    int expectedWidth = width / inSampleSize;

    if (expectedWidth > reqWidth) {
        inSampleSize = Math.round((float) width / (float) reqWidth);
    }
    options.inSampleSize = inSampleSize;
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}

但这是他们正确的方法吗?因为我看到了建议compression operation takes rather big amount of time here

的答案

10 个答案:

答案 0 :(得分:50)

效果很好试试这个

private String decodeFile(String path,int DESIREDWIDTH, int DESIREDHEIGHT) {
        String strMyImagePath = null;
        Bitmap scaledBitmap = null;

        try {
            // Part 1: Decode image
            Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingLogic.FIT);

            if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
                // Part 2: Scale image
                scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingLogic.FIT);
            } else {
                unscaledBitmap.recycle();
                return path;
            }

            // Store to tmp file

            String extr = Environment.getExternalStorageDirectory().toString();
            File mFolder = new File(extr + "/TMMFOLDER");
            if (!mFolder.exists()) {
                mFolder.mkdir();
            }

            String s = "tmp.png";

            File f = new File(mFolder.getAbsolutePath(), s);

            strMyImagePath = f.getAbsolutePath();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(f);
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            } catch (Exception e) {

                e.printStackTrace();
            }

            scaledBitmap.recycle();
        } catch (Throwable e) {
        }

        if (strMyImagePath == null) {
            return path;
        }
        return strMyImagePath;

    }

<强> ScalingUtilities.java

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

/**
 * Class containing static utility methods for bitmap decoding and scaling
 *
 * @author 
 */
public class ScalingUtilities {

    /**
     * Utility function for decoding an image resource. The decoded bitmap will
     * be optimized for further scaling to the requested destination dimensions
     * and scaling logic.
     *
     * @param res The resources object containing the image data
     * @param resId The resource id of the image data
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Decoded bitmap
     */
    public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);

        return unscaledBitmap;
    }
    public static Bitmap decodeFile(String path, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options);

        return unscaledBitmap;
    }

    /**
     * Utility function for creating a scaled version of an existing bitmap
     *
     * @param unscaledBitmap Bitmap to scale
     * @param dstWidth Wanted width of destination bitmap
     * @param dstHeight Wanted height of destination bitmap
     * @param scalingLogic Logic to use to avoid image stretching
     * @return New scaled bitmap object
     */
    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

        return scaledBitmap;
    }

    /**
     * ScalingLogic defines how scaling should be carried out if source and
     * destination image has different aspect ratio.
     *
     * CROP: Scales the image the minimum amount while making sure that at least
     * one of the two dimensions fit inside the requested destination area.
     * Parts of the source image will be cropped to realize this.
     *
     * FIT: Scales the image the minimum amount while making sure both
     * dimensions fit inside the requested destination area. The resulting
     * destination dimensions might be adjusted to a smaller size than
     * requested.
     */
    public static enum ScalingLogic {
        CROP, FIT
    }

    /**
     * Calculate optimal down-sampling factor given the dimensions of a source
     * image, the dimensions of a destination area and a scaling logic.
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal down scaling sample size for decoding
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcWidth / dstWidth;
            } else {
                return srcHeight / dstHeight;
            }
        } else {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcHeight / dstHeight;
            } else {
                return srcWidth / dstWidth;
            }
        }
    }

    /**
     * Calculates source rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal source rectangle
     */
    public static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.CROP) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                final int srcRectWidth = (int)(srcHeight * dstAspect);
                final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
                return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
            } else {
                final int srcRectHeight = (int)(srcWidth / dstAspect);
                final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2;
                return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
            }
        } else {
            return new Rect(0, 0, srcWidth, srcHeight);
        }
    }

    /**
     * Calculates destination rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal destination rectangle
     */
    public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect));
            } else {
                return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight);
            }
        } else {
            return new Rect(0, 0, dstWidth, dstHeight);
        }
    }

}

答案 1 :(得分:44)

我使用此功能在上传之前缩小图像的大小,它将图像大小减小到接近200 KB并保持质量相对较好,您可以通过更改REQUIRED_SIZE和inSampleSize来修改它以实现您的目的:

public File saveBitmapToFile(File file){
    try {

        // BitmapFactory options to downsize the image
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        o.inSampleSize = 6;
        // factor of downsizing the image

        FileInputStream inputStream = new FileInputStream(file);
        //Bitmap selectedBitmap = null;
        BitmapFactory.decodeStream(inputStream, null, o);
        inputStream.close();

        // The new size we want to scale to
        final int REQUIRED_SIZE=75;

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
                        o.outHeight / scale / 2 >= REQUIRED_SIZE) {
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        inputStream = new FileInputStream(file);

        Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
        inputStream.close();

        // here i override the original image file
        file.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(file);

        selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100 , outputStream);

        return file;
    } catch (Exception e) {
        return null;
    }
}

注意:我在此功能中调整大小并覆盖原始文件图像,您也可以将其写入另一个文件。

我希望它可以帮助你。

答案 2 :(得分:1)

这是我的解决方案

/*
* This procedure will replace the original image
* So you need to do a tmp copy to send before reduce
*/
public static boolean reduceImage(String path, long maxSize) {
    File img = new File(path);
    boolean result = false;
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap = null;
    options.inSampleSize=1;
    while (img.length()>maxSize) {
        options.inSampleSize = options.inSampleSize+1;
        bitmap = BitmapFactory.decodeFile(path, options);
        img.delete();
        try
            {
                FileOutputStream fos = new FileOutputStream(path);
                img.compress(path.toLowerCase().endsWith("png")?
                                Bitmap.CompressFormat.PNG:
                                Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();
                result = true;
             }catch (Exception errVar) { 
                errVar.printStackTrace(); 
             }
    };
    return result;
}

编辑删除了其他程序调用

答案 3 :(得分:1)

这是一种在内存中处理的解决方案,不需要实际在文件系统上生成文件。

在某些片段中,用户选择了图像文件后:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if (imageReturnedIntent == null
            || imageReturnedIntent.getData() == null) {
        return;
    }

    // aiming for ~500kb max. assumes typical device image size is around 2megs
    int scaleDivider = 4; 


    try {

        // 1. Convert uri to bitmap
        Uri imageUri = imageReturnedIntent.getData();
        Bitmap fullBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);

        // 2. Get the downsized image content as a byte[]
        int scaleWidth = fullBitmap.getWidth() / scaleDivider;
        int scaleHeight = fullBitmap.getHeight() / scaleDivider;
        byte[] downsizedImageBytes =
                getDownsizedImageBytes(fullBitmap, scaleWidth, scaleHeight);

        // 3. Upload the byte[]; Eg, if you are using Firebase
        StorageReference storageReference =
                FirebaseStorage.getInstance().getReference("/somepath");

        storageReference.putBytes(downsizedImageBytes);
    }
    catch (IOException ioEx) {
        ioEx.printStackTrace();
    }
}

public byte[] getDownsizedImageBytes(Bitmap fullBitmap, int scaleWidth, int scaleHeight) throws IOException {

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(fullBitmap, scaleWidth, scaleHeight, true);

    // 2. Instantiate the downsized image content as a byte[]
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] downsizedImageBytes = baos.toByteArray();

    return downsizedImageBytes;
}

感谢:

答案 4 :(得分:0)

此代码缩小尺寸图像

private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//Compression quality, here 100 means no compression, the storage of compressed data to baos
        int options = 90;
        while (baos.toByteArray().length / 1024 > 400) {  //Loop if compressed picture is greater than 400kb, than to compression
            baos.reset();//Reset baos is empty baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//The compression options%, storing the compressed data to the baos
            options -= 10;//Every time reduced by 10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//The storage of compressed data in the baos to ByteArrayInputStream
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//The ByteArrayInputStream data generation
        return bitmap;
    }

答案 5 :(得分:0)

这是iam在 kotlin 中使用的方法:

注意:我尝试了3张图像,每张图像都是 6 mb ,并且在一个通话中

 private fun Bitmap.compress(cacheDir: File, f_name: String): File? {
    val f = File(cacheDir, "user$f_name.jpg")
    f.createNewFile()
    ByteArrayOutputStream().use { stream ->
        compress(Bitmap.CompressFormat.JPEG, 70, stream)
        val bArray = stream.toByteArray()
        FileOutputStream(f).use { os -> os.write(bArray) }
    }//stream
    return f
}

答案 6 :(得分:0)

@MBH的答案具有一种奇怪且不必要的获取结果的方法,如果文件的像素数大于6X REQUIRED_SIZE = 75;,则可能导致while循环被忽略。 o.inSampleSize = 6;是造成这种情况的原因,并且只能成功地卷积轴向像素的允许数量(6 * 75 = 450)。以下是MBH答案的翻新版本,其中还包括一个选项,不仅可以根据像素进行调整,还可以根据存储大小进行调整:

//This is the number of pixels that the width and height of the image will be allotted
//Note that the number of pixels implies (but does not exclusively determine) the file size of the image
private int REQUIRED_SIZE = 720;
//Method allows image files to be compressed to a standard maximum size
public void saveBitmapToFile(){

    try {

        //Initialize BitmapFactory options to downsize the image
        BitmapFactory.Options o = new BitmapFactory.Options();
        //Image dimensions do not change with change in pixel density
        o.inJustDecodeBounds = true;

        //Retrieve file and decode into bitmap, then close the stream when decode complete
        FileInputStream inputStream = new FileInputStream(imageFile);
        BitmapFactory.decodeStream(inputStream, null, o);
        inputStream.close();

        //Start with 1:1 scale size
        int scale = 1;

        while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) {
            //Find the correct scale value. It should be the power of 2.
            scale *= 2;
        }

        //Create new Bitmap options instance to adjust the image scale...(1/2)
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        //...then apply with new input stream
        inputStream = new FileInputStream(imageFile);
        Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
        inputStream.close();

        //Overwrite original file (type 'File') then compress the output file
        imageFile.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(imageFile);
        selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        //maxImageSize is arbitrary file size (byte) limit
        if(imageFile.length() < maxImageSize) {

            //Set image in place and get the uri
            imagePost.setImageURI(imageUri);

            //Reset in case decreased previously
            REQUIRED_SIZE = 720;

        } else {

            Toast.makeText(PostActivity.this, "Your image is " + (imageFile.length() - maxImageSize) / 1000 + "kb too large to upload. Reattempting...", Toast.LENGTH_LONG).show();

            REQUIRED_SIZE = REQUIRED_SIZE - 240;

            //Loop method until goal file size achieved
            saveBitmapToFile();

        }

    } catch (Exception ignored) {

    }

}

答案 7 :(得分:0)

    protected void Page_Load(object sender, EventArgs e)
    {
        //BR**
        string filePath = "";//Source file path with image name
        int CompressLevel = 50;//Image compression leve as per our requirement
        string DestintionPath = "";//Destination file path
        string Filename = "";//Output image name to save in destination path

        Stream bmpStream = System.IO.File.Open(filePath, System.IO.FileMode.Open);
        Bitmap bmp1 = new Bitmap(bmpStream);

        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, CompressLevel);
        myEncoderParameters.Param[0] = myEncoderParameter;
        bmp1.Save(DestintionPath + "\\" + Filename, jpgEncoder, myEncoderParameters);
        //BR**
        bmpStream.Close();
        string lblmsg = "Compressed Sucessfully with Compression Level { " + CompressLevel.ToString() + " }";
    }

答案 8 :(得分:0)

您可以使用这个名为 Compressor 的库。

压缩图像文件

val compressedImageFile = Compressor.compress(context, actualImageFile)
Compress Image File to specific destination
val compressedImageFile = Compressor.compress(context, actualImageFile) {
    default()
    destination(myFile)
}

自定义压缩器

使用默认约束和自定义部分

  val compressedImageFile = 
       Compressor.compress(context, actualImageFile) {
        default(width = 640, format = Bitmap.CompressFormat.WEBP)
    }

完全自定义约束

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    resolution(1280, 720)
    quality(80)
    format(Bitmap.CompressFormat.WEBP)
    size(2_097_152) // 2 MB
}

使用自己的自定义约束

class MyLowerCaseNameConstraint: Constraint {
    override fun isSatisfied(imageFile: File): Boolean {
        return imageFile.name.all { it.isLowerCase() }
    }

    override fun satisfy(imageFile: File): File {
        val destination = File(imageFile.parent, imageFile.name.toLowerCase())
        imageFile.renameTo(destination)
        return destination
    }
}

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    constraint(MyLowerCaseNameConstraint()) // your own constraint
    quality(80) // combine with compressor constraint
    format(Bitmap.CompressFormat.WEBP)
}

创建 Kotlin 扩展 -

fun Compression.lowerCaseName() {
    constraint(MyLowerCaseNameConstraint())
}

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    lowerCaseName() // your own extension
    quality(80) // combine with compressor constraint
    format(Bitmap.CompressFormat.WEBP)
}

使用 Kotlin 协程压缩图像 -

// e.g calling from activity lifecycle scope
lifecycleScope.launch {
    val compressedImageFile = Compressor.compress(context, actualImageFile)
}

// calling from global scope
GlobalScope.launch {
    val compressedImageFile = Compressor.compress(context, actualImageFile)
}

在主线程中运行 Compressor -

val compressedImageFile = Compressor.compress(context, actualImageFile, Dispatchers.Main)

enter image description here

答案 9 :(得分:-1)

使用此方法返回压缩到大约200 KB的位图图像。您可以对其进行配置,以获得您想要的任何大小的位图图像。

#if defined(Q_OS_ANDROID)
QAndroidJniObject activity = QtAndroid::androidActivity();
if (activity.isValid()) {
    QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;");

    if (window.isValid()) {
        const int FLAG_KEEP_SCREEN_ON = 128;
        window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
    }
    QAndroidJniEnvironment env; if (env->ExceptionCheck()) { env->ExceptionClear(); } //Clear any possible pending exceptions.
}
#endif