Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to find an image compression algorithm in the Swift programming language, as in the WhatsApp messenger. In the programming language Java under OS Android I found quickly, and under the platform iOS have difficulties.

Here is the image compression algorithm for Android:


Java
public static 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, 70 , outputStream);

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


This algorithm compresses the image to 100 KB. If you can tell me how to duplicate this code into the Swift programming language, I'll be very grateful.


What I have tried:

I have studied many articles, tried to use different algorithms (unfortunately I can not publish them, because I do not remember the sites), but I did not find the necessary solution.
Posted
Updated 20-Aug-18 12:19pm

1 solution

Quote:
This algorithm compresses the image to 100 KB.

No, this code do not compress the image to given size, it downscale the image. The reduced size is only a secondary effect.
Quote:
I'm trying to find an image compression algorithm

You are not looking for a compression algorithm jpeg images are already compressed.
What you are looking for is a library that will allow you to resize the images.
 
Share this answer
 
Comments
Member 13955667 21-Aug-18 5:04am    
ppolymorphe, do you have any sample code that will help me?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900