Hello I have images in File. How can I compress and reduce the file size as well as find out its size?

  • 2
    File size, in bytes: long size = file.length(); . And about the compression you need to clarify: what we have and what we want to get. Most image formats are already compressed, so compression without loss of quality is ineffective. The larger effect is the reduction in size (in pixels), but the quality is lost. - woesss
  • @woesss Hello. We have a File object in which the images from the gallery. You need to get a smaller File to send to the server. At first I thought Get Bitmap and then turn it into File. But I did not find a way to do this. I need to post this file in okhttp3.RequestBody and send it to the server using retrofit2. I would be glad to hear alternatives - Fariz Mamedow
  • I'll try to ask in another way: Why do I need to compress it? Does the server have any restrictions? Or in order to save traffic? You can decode using the BitmapFactory class (here a little bit about loading a reduced copy into memory: Load a Scaled Down Version into Memory ), make any transformations and compress already familiar to you Bitmap.compress() - woesss
  • @woesss in order to save traffic and server resources. Suppose I decoded the bitmap squeezed and in the end I am left with a bitmap file that cannot be sent using the retrofit. For a retrofit, you need images in the File object. - Fariz Mamedow
  • one
    What do you call a bitmap file that cannot be sent using a retrofit ? - woesss

1 answer 1

Compress files can be simply archiving them. Java provides functionality for working with such kind of files as ZIP archives: article.

You can find out the file size in this way.

  • Hello. I do not think that this is suitable. I just need to reduce the file size for future upload to the server. Do you offer to send zip? I need something like Bitmap.compress () only for a file or a way to get a file from a bitmap - Fariz Mamedow
  • @ user8978194, to be honest, I do not think that there is any particular way to properly compress the image without loss. For ordinary text, binary files - the same. In such cases, ZIP-archiving usually helps - it gives maybe 5% compression, not more. If you are satisfied with the loss of image quality, then convert it to WEBP format, it is just supported by Android devices. - nick
  • WebP is already interesting. Are there libraries for android? - Fariz Mamedow 4:41 pm
  • @ user8978194, google.com/… - nick
  • @ user8978194, the first 4 search results should be useful. - nick