Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import static android.graphics.Bitmap.*;

public class Main {

    public static String scaleImageFile(String filepath, int targetSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        File file = new File(filepath);
        float scaleFactor = file.length() / targetSize;
        options.inSampleSize = Math.round(scaleFactor);
        Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);

        int dotPos = filepath.lastIndexOf('.');
        String newFilePath = String.format("%s_scaled.%s", filepath.substring(0, dotPos),
                filepath.substring(dotPos + 1, filepath.length()));
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(newFilePath);
            if (!bitmap.compress(CompressFormat.JPEG, 90, fos)) {
                newFilePath = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            newFilePath = null;
        }
        bitmap.recycle();
        return newFilePath;
    }
}