Android 上传前,向下采样图像低于大小限制

Android 上传前,向下采样图像低于大小限制,android,Android,在我需要上传图像的服务器上有2MB的限制 我正在使用此方法对位图进行下采样 在这种方法中 public InputStream getPhotoStream(int imageSizeBytes) throws IOException { int targetLength = 1500; ByteArrayOutputStream photoStream; byte[] photo; Bitmap pic; fina

在我需要上传图像的服务器上有2MB的限制

我正在使用此方法对位图进行下采样

在这种方法中

public InputStream getPhotoStream(int imageSizeBytes) throws IOException {
        int targetLength = 1500;
        ByteArrayOutputStream photoStream;
        byte[] photo;
        Bitmap pic;
        final int MAX_QUALITY = 100;
        int actualSize = -1;
        do {
            photo = null;
            pic = null;
            photoStream = null;

            //this calls the downsampling method
            pic = getPhoto(targetLength);

            photoStream = new ByteArrayOutputStream();
            pic.compress(CompressFormat.JPEG, MAX_QUALITY, photoStream);
            photo = photoStream.toByteArray();
            actualSize = photo.length;
            targetLength /= 2;
        } while (actualSize > imageSizeBytes);
        return new ByteArrayInputStream(photo);
}

这会在第二次迭代时抛出OutOfMemoryError。如何将图像缩小到某个大小限制以下?

我认为出现问题的原因是您正在将图像压缩为内存中的表示形式,您需要在尝试再次压缩之前释放该内存

您需要在photoStream中调用
close()
,然后重试以释放资源。 另外,
toByteArray()
在内存中创建一个流的副本,您以后必须释放它,为什么不使用
photoStream.size()
来检查文件大小呢

如果您需要,我可以发布一些代码。

而不是以下内容:

pic = null;
这样做:

if (pic!=null)
    pic.recycle();
pic = null
如果只是将位图对象设置为null,则不会立即释放它占用的内存。在第二种情况下,您明确地告诉操作系统您已经完成了位图的处理,并且可以释放它的内存


也考虑使用90的压缩质量,而不是100,我相信这会减少文件的大小。

谢谢,不幸的是,我仍然在内存不足。