开发者

Resize image to exact file size

Actually i am developing one application, where my requirement is like i have to scale large size images to some predefined size as per user selection. eg,Suppose i have an image whic开发者_StackOverflow社区h is of 1Mb and user select it to convert it into an image of size 100kb then i have to resize that image to 100kb. last one day i am trying to achevive this with Bitmap APIs but i am not able to achieve the exact size what user want. Sometimes its very large sometimes very small. So please if anyone knows how to resize image in android to exact size(which is changing as per user selection). Please help me out in this.


If only the file size matters, you will want to use an image file format that does not use compression. You should be able to take an image with attributes such as width, height, bit-depth, and so on and calculate the expected file size for such an image.

So, using such a file format you start with your original image and you have

File size = width x height x bit depth + metadata/overhead.

I assume you want to maintain the original aspect ratio also. In that case, you can probably just figure out the % reduction in file size from the current file size, and multiply the width and height by the same %. Scale your image using a bitmap image manipulation API and then save it. It should be close to the file size you are looking for.

Specific to the Android Bitmap api you can use getByteCount() to determine how many bytes the image currently takes up. You can also use getConfig() to determine how many bytes per pixel.

So, your final goal file size converted to bytes divided by the number of bytes per pixel, gives you the number of pixels you are allowed. Number of pixels allowed divided by the number of pixels in your current image will give you the scaling factor. Use the scaling factor and scale the image keeping the current aspect ratio and you should have a bitmap with a number of pixels close to your goal. Then save in a file format that does not use compression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜