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 java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;

import android.os.Environment;

import android.util.Log;

public class Main {
    public static final String TAG = "AirImagePicker";

    public static String saveImageToTemporaryDirectory(Bitmap image) {
        Log.d(TAG, "[AirImagePickerUtils] Entering saveImageToTemporaryDirectory");
        String path = "";
        FileOutputStream outputStream;
        try {
            File file = getTemporaryFile(".jpg");
            outputStream = new FileOutputStream(file);
            outputStream.write(getJPEGRepresentationFromBitmap(image));
            outputStream.close();
            path = file.getAbsolutePath();
            Log.d(TAG, "[AirImagePickerUtils] saveImageToTemporaryDirectory path:" + path);
        } catch (IOException e) {
            Log.e(TAG, "[AirImagePickerUtils] saveImageToTemporaryDirectory error:" + e.toString());
            // Error while creating file
        }
        Log.d(TAG, "[AirImagePickerUtils] Exiting saveImageToTemporaryDirectory");
        return path;
    }

    static public File getTemporaryFile(String extension) {
        // Get or create folder for temp files
        File tempFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "airImagePicker");
        if (!tempFolder.exists()) {
            tempFolder.mkdirs();
            try {
                new File(tempFolder, ".nomedia").createNewFile();
            } catch (Exception e) {
                Log.e(TAG, "Couldn't create temporary file with extension '" + extension + "'");
            }
        }

        // Create temp file
        try {
            return new File(tempFolder, String.valueOf(System.currentTimeMillis()) + extension);
        } catch (Exception e) {
            Log.e(TAG, "Couldn't create temp file");
        }
        return null;
    }

    static public byte[] getJPEGRepresentationFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
        return outputStream.toByteArray();
    }
}