-3

In my app I have to upload selected images to parse.com for taking their Printout . I have to maintain image quality and I could not resize the images. I have to upload images in the parse.com ..I do not need to show them on device screen (images are form image gallery or from facebook album..or from sdcard) . I could not scale down them as per requirement.

I am getting OutOfMemory error on BitmapFactory.decodeFile(). How to solve this bug ?

is using android:largeHeap="true" could sove my issue ?

I am getting this crash on Samsung SM-G900T, But not on emulator ..

I tried to put

BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inJustDecodeBounds = false;
                                options.inPreferredConfig = Config.RGB_565;

But it is not working. Below is my AsyncTask class for uploading images to Parse.com

class UploadFileFromURL extends AsyncTask<String, String, String> {
    ProgressDialog dialog;
    String albumId = "";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }


    @Override
    protected String doInBackground(String... f_url) {

        try {
            for (int i = 0; i < arrListImgBean.size(); i++) {

                if (!isUploading || objAsyncUpload.isCancelled()) {
                    break;
                }
                try {
                    if (arrListImgBean.get(i).imageStatus == 1)
                        continue;
                    else if (arrListImgBean.get(i).imageStatus == 2) {
                        isPhotodeleted = true;
                        publishProgress("" + countUploaded);
                        deletePhoto(i);

                    }

                    else {
                        isPhotodeleted = false;
                        try {

                            Bitmap b = null;
                            InputStream is = null;
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = false;
                            options.inPreferredConfig = Config.RGB_565; // to
                                                                        // reduce
                                                                        // the
                                                                        // memory
                            options.inDither = true;
                            if (arrListImgBean.get(i).imgURL
                                    .startsWith("http")) {
                                try {
                                    URL url = new URL(
                                            arrListImgBean.get(i).imgURL);
                                    is = url.openConnection()
                                            .getInputStream();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                b = BitmapFactory.decodeStream(is, null,
                                        options);

                            } else {
                                b = BitmapFactory.decodeFile(
                                        arrListImgBean.get(i).imgURL,
                                        options);
                            }

                            // Convert it to byte
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            // Bitmap out = Bitmap.createScaledBitmap(b,
                            // 1500, 2100, false);
                            b.compress(Bitmap.CompressFormat.PNG, 100,
                                    stream);
                            byte[] image = stream.toByteArray();
                            ParseFile file = new ParseFile("Android.png",
                                    image);
                            file.save();
                            String uploadedUrl = file.getUrl();
                            if (uploadedUrl != null) {

                                ParseObject imgupload = new ParseObject(
                                        "Photo");
                                imgupload.put("userName", ParseUser
                                        .getCurrentUser().getEmail());
                                imgupload.put("photoURL", file);
                                imgupload.put("photoID",
                                        arrListImgBean.get(i).imageId);
                                imgupload.put("count", 1);
                                imgupload.put("albumName", albumId);
                                imgupload.save();
                                String objId = imgupload.getObjectId();

                                if (objId != null && !objId.isEmpty()) {
                                    countUploaded++;
                                    publishProgress("" + countUploaded);

                                    database.updateImageStatus(
                                            arrListImgBean.get(i).imageId,
                                            Constants.STATUS_UPLOADED,
                                            objId, uploadedUrl);
                                }

                            }

                        } catch (Exception e) {

                        }

                    }
                } catch (Exception e) {
                    isUploading = false;
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;

    }



    @Override
    protected void onPostExecute(String file_url) {
        // dismissDialog(progress_bar_type);
        isUploading = false;
        btnUploadImages.setBackgroundResource(R.drawable.upload_photo);
        vprogress.setCompoundDrawables(null, null, null, null);
        // stopLoading();
        setProgressMsg();

    }

}
Nibha Jain
  • 7,742
  • 11
  • 47
  • 71
  • can't u scale down your image while loading into memory ? – Atmaram Jun 29 '15 at 10:16
  • `android:largeHeap="true"` isn't made for this scenario. It was made for resource extensive apps like photo editing softwares, etc which uses a lot of memory. What u need to do here is to scale down the image according to the device screen. – Rohan Kandwal Jun 29 '15 at 10:16
  • There are `>1k` such a questions available in SO. – M D Jun 29 '15 at 10:42
  • I am looking for the solution , you can check my code I already took all the precautions suggested in those >1k questions @MD – Nibha Jain Jun 29 '15 at 10:45
  • I will ask again, what is the needed image quality and what is the needed image size? – Rohan Kandwal Jun 29 '15 at 12:08

3 Answers3

0
android:largeHeap="true"

This line of code can solve your problem but its a temporary solution but crash may occurs again if number of images or the size of images will increase. Better to Use Picasso library to deals with Images

Balvinder Singh
  • 580
  • 6
  • 19
0

Consider you have an image of 1024x1024dp and a device with 512x512dp (both figures are just for understanding). So, in this case, loading a full resolution image on a smaller scale device is waste of memory. What you can do is to scale down the image so that it fits the device screen. In this way not only you will save a lot of memory but also get a proper, clear and sharp image.

I am adding code for scaling the image which I am using currently in my project.

final FileInputStream streamIn = new FileInputStream(file);
final BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = true;
//  Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 300;
int width_tmp = ops.outWidth, height_tmp = ops.outHeight;
int scale = 1;
while (true) {
      if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
             break;
            }
      width_tmp /= 2;
      height_tmp /= 2;
      scale *= 2;
 }

 ops.inJustDecodeBounds = false;
 ops.inSampleSize = scale;
 bitmap = BitmapFactory.decodeStream(streamIn, null, ops); //This gets the image
 streamIn.close();

Choose a REQUIRED_SIZE value depending on the device's screen display size.

Rohan Kandwal
  • 9,112
  • 8
  • 74
  • 107
  • I have to upload images in the parse.com ..I do not need to show them on device screen (images are form image gallery or from facebook album..) I could not scale down them as per requirement. – Nibha Jain Jun 29 '15 at 10:29
  • 1
    What is "as per requirement"? A definitive size? – Rohan Kandwal Jun 29 '15 at 10:32
0
        try {
            image = readInFile(path);
        }
        catch(Exception e) { 
            e.printStackTrace();
        }

        // Create the ParseFile
        ParseFile file = new ParseFile("picturePath", image);
        // Upload the image into Parse Cloud
        file.saveInBackground();

        // Create a New Class called "ImageUpload" in Parse
        ParseObject imgupload = new ParseObject("Image");

        // Create a column named "ImageName" and set the string
        imgupload.put("Image", "picturePath");


        // Create a column named "ImageFile" and insert the image
        imgupload.put("ImageFile", file);

        // Create the class and the columns
        imgupload.saveInBackground();

        // Show a simple toast message
        Toast.makeText(LoadImg.this, "Image Saved, Upload another one ",Toast.LENGTH_SHORT).show();


 private byte[] readInFile(String path) throws IOException {
     // TODO Auto-generated method stub
     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();

 }
Ravi
  • 34,851
  • 21
  • 122
  • 183