Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sephiroth74
Created January 16, 2016 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sephiroth74/de8f9832a6702c712d85 to your computer and use it in GitHub Desktop.
Save sephiroth74/de8f9832a6702c712d85 to your computer and use it in GitHub Desktop.
Utility class to save and load bitmap to and from a bundle. Use it for onSaveInstanceState/onCreate lifecycle
public static class BitmapRetention {
public static Bundle safeSave (@NonNull final Bitmap bitmap) {
try {
return save(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Bundle save (@NonNull final Bitmap bitmap) throws IOException {
if (bitmap.isRecycled()) {
return null;
}
final int total = bitmap.getByteCount();
if (total == 0) {
return null;
}
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(total);
bitmap.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
File file = File.createTempFile("savedBitmap", ".bmp");
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
final FileChannel fileChannel = accessFile.getChannel();
fileChannel.write(byteBuffer);
fileChannel.close();
accessFile.close();
Bundle bundle = new Bundle();
bundle.putString("src.uri", file.getAbsolutePath());
bundle.putString("src.config", bitmap.getConfig().name());
bundle.putInt("src.width", bitmap.getWidth());
bundle.putInt("src.height", bitmap.getHeight());
return bundle;
}
public static Bitmap safeLoad (@Nullable Bundle bundle) {
if (null == bundle) {
return null;
}
try {
return load(bundle);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Bitmap load (@NonNull final Bundle bundle) throws IOException {
final int width = bundle.getInt("src.width", 0);
final int height = bundle.getInt("src.height", 0);
final String config = bundle.getString("src.config", null);
final String uri = bundle.getString("src.uri", null);
if (width < 1 || height < 1 || TextUtils.isEmpty(config) || TextUtils.isEmpty(uri)) {
Log.w(TAG, "width=" + width + ", height=" + height + ", config=" + config + ", uri=" + uri);
return null;
}
File file = new File(uri);
RandomAccessFile accessFile = new RandomAccessFile(file, "r");
FileChannel channel = accessFile.getChannel();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
buffer.load();
try {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.valueOf(config));
bitmap.copyPixelsFromBuffer(buffer);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
channel.close();
accessFile.close();
file.delete();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment