outOfMemory Exception while re-encoding image - java

I'm trying to encode an image to 64 base ,
after choosing the image from gallery and trying to save it I am getting this error:
outOfMemory Exception
can any one suggest how to to get this image to base 64 without memory error?
MotorImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
String imageString = null;
try {
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
bm.recycle();
byte[] b = baos.toByteArray();
imageString = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), imageString, Toast.LENGTH_SHORT).show();

I suspect you need to scale and resample your image to fit within the constraints on the device, try something like this
// decodes image and scales it to reduce memory consumption
private Bitmap decodeImage(String picturePath) {
try {
File file = new File(picturePath);
// Get image size
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, opts);
// The new size we want to scale to
final int MIN_SIZE = 70;
// Find the correct scale value.
int scale = 1;
while (((opts.outWidth / scale) >> 1) >= MIN_SIZE
&& ((opts.outHeight / scale) >> 1) >= MIN_SIZE) {
scale <<= 1;
}
BitmapFactory.Options opts2 = new BitmapFactory.Options();
opts2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opts2);
} catch (FileNotFoundException e) {
}
return null;
}

Try to use android:largeHeap="true" inside the application tag on AndroidManifest, then your app will have more ram available and will not throw a oom exception.

If you read the official document of android you will come to know that this is a common issue with android and the recommended solution is to resize image according to your need. you can refer developer.android for this as well

Related

How to resize camera or gallery photo

I choose a file from gallery or camera. Then I'll upload them to the server. But I can't reduce their size. Image quality does not matter. Can you tell me the best method? I'm a beginner and I don't know how to use the code. So please give details.
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.myapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Glide.with(this).load(currentPhotoPath).into(iv);
} else if (requestCode == SELECT_A_PHOTO && resultCode == RESULT_OK){
selectedPhoto = data.getData();
Glide.with(this).load(selectedPhoto).into(iv);
}
private void galleryIntent()
{
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,SELECT_A_PHOTO);
}
My file sizes look like this
I found the answer.This method allows you to reduce the size.
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
New image size
This function takes in the image path and converts into a bitmap. 700 is the basic threshold for height/width set by me here. You can change it accordingly and create a scaled bitmap (The lower the number, lower is the image size). Each iteration of the while loop reduces the image to half. You can remodify it as per your requirement.
private Bitmap reduce_image_to_bitmap(String file_path){
Bitmap bit_map = BitmapFactory.decodeFile(file_path);
int h = bit_map.getHeight();
int w = bit_map.getWidth();
while(h > 700 || w > 700){
h = h/2;
w = w/2;
}
Bitmap out = Bitmap.createScaledBitmap(bit_map, w, h, false);
return out;
}
Make sure to convert the bitmap to a file and then proceed to send the file to your server.
Use this library: Compressor
Compressor is a lightweight and powerful android image compression library. Compressor will allow you to compress large photos into smaller sized photos with very less or negligible loss in quality of the image.
First of all you need to process this image so that you can reduce the size but quality you can maintain. You need to run a background task so that during big image process device doesn't fizz.
Then you can show a progress dialog during this process just add this code into your onCreate activity.
public ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog = new ProgressDialog(MyProfileEidtActivity.this);
progressDialog.setMessage("Loading ...");
// just execute this process
new ImageProcessing().execute("YOUR IMAGE PATH");
}
public class ImageProcessing extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Image Processing");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
Bitmap mainImage = null;
Bitmap converetdImage = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try {
mainImage = BitmapFactory.decodeFile(strings[0]);
/// 500 means image size will be maximum 500 kb
converetdImage = getResizedBitmap(mainImage, 500);
bos = new ByteArrayOutputStream();
converetdImage.compress(Bitmap.CompressFormat.JPEG, 50, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return encodeString;
}
#Override
protected void onPostExecute(String image) {
super.onPostExecute(s);
progressDialog.dismiss();
// this image will be your reduced image path
}
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}

Why can't I get an image from the camera album in Android gallery?

I can get images from the gallery, but I can't get from the camera album/roll. But I know I got the URI of an image from the camera roll and still it won't show up in my imageview.
Opening the Gallery:
if(resultCode == RESULT_OK){
imgUri = data.getData();
if(requestCode == PICK_IMAGE){
Intent sendpic = new Intent(getApplicationContext(), GalleryChoice.class);
sendpic.putExtra("imagePath", imgUri.toString());
Log.d("SHOW UP", imgUri.toString());
startActivity(sendpic);
Getting the URI from the previous activity to show up in the ImageView, where the image is not showing up.
if(getIntent().hasExtra("imagePath")){
ur = getIntent().getStringExtra("imagePath");
Uri newUri = Uri.parse(ur);
try {
bitmapy = MediaStore.Images.Media.getBitmap(this.getContentResolver(), newUri);
imgView1.setImageBitmap(bitmapy);
}
catch (IOException e){
}
}
Check if Uri is valid. If it's, use method below to get it's real address.
public String getRealPathFromURI(Uri uri){
String filePath = "";
String[] filePahColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePahColumn, null, null, null);
if (cursor != null) {
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePahColumn[0]);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
}
Use this filePath to set your image
yourImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
You can use this to scale down your image.
It generally happens when the Image is large is size which is 2048*2048. Generally camera roll captures images larger in size, if the image has any length and width sized more than 2048, It require cropping.
Valid size to set on ImageView < 2048*2048, from camera roll
Below is just an example to crop image if large in size,and does not take care of image ratio
public class InputImageCompressor extends Activity{
public static void compressInputImage(Uri inputImageData, Context context, ImageView newIV)
{
Bitmap bitmap;
//Uri inputImageData = data.getData();
try
{
Bitmap bitmapInputImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), inputImageData);
if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() > 2048)
{
bitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true);
newIV.setImageBitmap(bitmap);
}
else if (bitmapInputImage.getWidth() > 2048 && bitmapInputImage.getHeight() < 2048)
{
bitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1920, 1200, true);
newIV.setImageBitmap(bitmap);
}
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() > 2048)
{
bitmap = Bitmap.createScaledBitmap(bitmapInputImage, 1024, 1280, true);
newIV.setImageBitmap(bitmap);
}
else if (bitmapInputImage.getWidth() < 2048 && bitmapInputImage.getHeight() < 2048)
{
bitmap = Bitmap.createScaledBitmap(bitmapInputImage, bitmapInputImage.getWidth(), bitmapInputImage.getHeight(), true);
newIV.setImageBitmap(bitmap);
}
} catch (Exception e)
{
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Use this in your code:
if(getIntent().hasExtra("imagePath")){
ur = getIntent().getStringExtra("imagePath");
Uri newUri = Uri.parse(ur);
try {
InputImageCompressor.compressInputImage(newUri, your_class_name.this, imgView1);
}
catch (IOException e){
}
}
Why image size limited to 2048*2048 read more

Get string data from selected image from gallery using Intent

I am developing an app and part of it is selecting image from phone gallery and post it as a string to web api. The problem is with my selection of image and turning it to string to send. Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_picker);
((Button) findViewById(R.id.buttonSelectMedia))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent, 2);
}
});
}
and my onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] arr = baos.toByteArray();
String stringImage = Base64.encodeToString(arr, Base64.DEFAULT);
String fileName = imageReturnedIntent.getData().getLastPathSegment();
}
I am getting an out of memmory exc on
String stringImage = Base64.encodeToString(arr, Base64.DEFAULT);
Regards to all.
I have found different path to the final result I am looking for. This is part of my OnActivityResult:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
String extension = filePath.substring(filePath.lastIndexOf(".")+1);
isBusy = true;
File file = new File(filePath);
FileInputStream mediaStream = new FileInputStream(file);
from this code I am able to do things like:
mediaStream.available()
and do my work. Regards to all and thanks for the help.
For avoiding the Out of Memory ecxeption in android while dealing with images you can use BitmapFactory.Options,Here is more information and code Loading Large Bitmaps Efficiently.

Uploading/saving selected image with Parse as backend

Ok guys, so after spending one day trying to figure out how to upload an image to parse servers i finally decided to ask for your help. I didn't find any full example on how to do this.
What i want to be able to do is:
select image from gallery (already did that)
load into inageView (already did that)
at onClick event upload the selected picture to Parse servers (my problem)
Here you have my code snippet so far, but it's not working.
private static int RESULT_LOAD_IMAGE = 1;
mSubmitJobBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createJob(); //this method will send data to Parse
}
});
private void addJob(final String mUsernameText, String mJobNameText,
String mJobDescriptionText, String mJobPriceText) {
/*Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
try {
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}*/
ParseUser user = ParseUser.getCurrentUser();
anunt.put("username", "andrei");
anunt.put("jobName", mJobNameText);
anunt.put("jobDescription", mJobDescriptionText);
anunt.put("jobPrice", mJobPriceText);
/*// Create a column named "jobPicture" and set the string
anunt.put("jobPicture", "picturePath");
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageFile" and insert the image
anunt.put("ImageFile", file);*/
anunt.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!", Toast.LENGTH_LONG)
.show();
Intent in = new Intent(getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up error, please check all the fields",
Toast.LENGTH_LONG).show();
}
}
});
}
public byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}***strong text***
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.addJob_imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
You should use PHP or any server script to upload image from android to the server. Try the URL given below,
Upload Image to Server PHP Android
this is the answer!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagez = stream.toByteArray();
ParseFile filez = new ParseFile("androidbegin.png",
imagez);
filez.saveInBackground();
imgupload = new ParseObject("Anunturi");
imgupload.put("JobPictureName", "AndroidBegin Logo");
imgupload.put("jobPicture", filez);
imgupload.put("jobPictureName", picturePath);
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
mGoogleNow
.setVisibility(mGoogleNow.INVISIBLE);
Toast.makeText(getApplicationContext(),
"An error occured",
Toast.LENGTH_LONG).show();
}
}
});
} else {
bitmap = null;
imgupload = new ParseObject("Anunturi");
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.put("jobPictureName", "null");
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(
getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(
getApplicationContext(),
"Error while posting job...",
Toast.LENGTH_LONG).show();
}
}
});

Implementing fix on Out of Memory Error

In my widget, I have an imageView that collect an image from the user gallery and then sets that image up as the background in another activity. It works fine, but when I try to add an image file that is too big (such as an image from the camera) or upload many image files, I get an "out of memory" error. After looking around stackoverflow for a while, I noticed that everyone pretty much used the basic method of:
public static Bitmap decodeSampleImage(File f, int width, int height) {
try {
System.gc(); // First of all free some memory
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int requiredWidth = width;
final int requiredHeight = height;
// Find the scale value (as a power of 2)
int sampleScaleSize = 1;
while (o.outWidth / sampleScaleSize / 2 >= requiredWidth && o.outHeight / sampleScaleSize / 2 >= requiredHeight)
sampleScaleSize *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleScaleSize;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (Exception e) {
Log.d(TAG, e.getMessage()); // We don't want the application to just throw an exception
}
return null;
}
I also noticed that people have recycled unused bitmaps as well. I understand how this works but I don't know where I should put it in my coding.
Here are my two classes (Personalize.java where the imageView to collect the background is. It has the imageView and two buttons (one for choosing an image from the gallery where it then displays that image into the imageView and the other to then set that image as the background).
First here is Personalize.java:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Personalize extends Activity implements View.OnClickListener {
Button button;
ImageView image; //the imageview for setting the background
ImageView image2; //the imageview for setting the icon (not focusing on)
Button btnChangeImage;
Button btnChangeImageForIcon;
Button btnSetBackground;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String selectedImagePath;
Bitmap background;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);
Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
btnChangeImage.setOnClickListener(this);
Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
btnChangeImageForIcon.setOnClickListener(this);
Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
btnSetBackground.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangeImage:
launchImageChooser();
break;
case R.id.btnChangeImageForIcon:
launchImageChooser();
break;
case R.id.btnSetBackground:
setBackgroundImageInDragAndDrop();
break;
}
}
private void setBackgroundImageInDragAndDrop() {
Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
ByteArrayOutputStream stream = new ByteArrayOutputStream();
background.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();
i.putExtra("myBackgroundBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if(cursor != null) {
cursor.close();
}
return imagePath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
background = getAndDecodeImage(selectedImagePath);
if(background != null){
image.setImageBitmap(background);
}
} else if (requestCode == SELECT_PICTURE_2)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap b2 = getAndDecodeImage(selectedImagePath);
if(b2 != null){
image2.setImageBitmap(b2);
}
}
}
}
private Bitmap getAndDecodeImage(String selectedImagePath){
try {
Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
return bMap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
}
Then here is my Drag_and_Drop_App.java (snippet of important parts -- collects bitmap and sets as background):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
// Link to Personalize Screen
btnLinkToPersonalize.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Personalize.class);
startActivityForResult(i, SET_BACKGROUND);
}
});
}
public Bitmap getThumbnail(String filename) {
Bitmap thumbnail = null;
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
return thumbnail;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode);
if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){
byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap");
Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
setBackgroundImage(myBackground);
}
}
#SuppressLint("NewApi")
private void setBackgroundImage(Bitmap bitmap) {
RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.rl_drag_and_drop_app);
Drawable d = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourBackgroundView.setBackgroundDrawable(d);
} else {
yourBackgroundView.setBackground(d);
}
}
}
So where could I implement that coding and where could I also get rid of other unused bitmaps in memory? (recycle them?)

Categories