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

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

public class Main {
    public static Bitmap convertToMutable(Bitmap srcBitmap, String cacheDirPath, String tempFileName) {
        try {
            // this is the file going to use temporally to save the bytes.
            // This file will not be a image, it will store the raw image data.
            int index = tempFileName.lastIndexOf(".");
            if (index != -1)
                tempFileName = tempFileName.substring(0, index);
            File file = new File(cacheDirPath + File.separator + tempFileName + ".tmp");

            // Open an RandomAccessFile
            // Make sure you have added uses-permission
            // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
            // into AndroidManifest.xml file
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

            // get the width and height of the source bitmap.
            int width = srcBitmap.getWidth();
            int height = srcBitmap.getHeight();
            Config type = srcBitmap.getConfig();

            // Copy the byte to the file
            // Assume source bitmap loaded using options.inPreferredConfig =
            // Config.ARGB_8888;
            FileChannel channel = randomAccessFile.getChannel();
            MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, srcBitmap.getRowBytes() * height);
            srcBitmap.copyPixelsToBuffer(map);
            // recycle the source bitmap, this will be no longer used.
            srcBitmap.recycle();
            System.gc();// try to force the bytes from the imgIn to be released

            // Create a new bitmap to load the bitmap again. Probably the memory
            // will be available.
            srcBitmap = Bitmap.createBitmap(width, height, type);
            map.position(0);
            // load it back from temporary
            srcBitmap.copyPixelsFromBuffer(map);
            // close the temporary file and channel , then delete that also
            channel.close();
            randomAccessFile.close();

            // delete the temp file
            file.delete();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return srcBitmap;
    }
}