Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.graphics.Bitmap;

import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.FileOutputStream;

public class Main {
    /**
     * @param maxSize unit kb
     */
    public static boolean compressSizeToFile(Bitmap bitmap, int maxSize, File outFile) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / 1024.0 > maxSize) {
            if (quality < 30) {
                break;
            }
            quality -= 20;
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            fileOutputStream.write(baos.toByteArray());
            fileOutputStream.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean compress(Bitmap bitmap, File outFile) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 35, baos);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            fileOutputStream.write(baos.toByteArray());
            fileOutputStream.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}