0

Hi I am unable to resize image using Picasso. I want to resize the image and send it to the server. I have saved the image to my internal directory and I am accessing it using mCurrentPhotoPath. The file gets uploaded to the server but it s not resized. Any help is appreciated.

private File createImageFile() throws IOException {

    OutputStream outStream = null;
    // 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 */
        );
    mCurrentPhotoPath = image.getAbsolutePath();
    try {
        outStream = new FileOutputStream(mCurrentPhotoPath);

        Bitmap bitmap = Picasso.get()
                               .load(mCurrentPhotoPath)
                               .resize(80, 80).fit()
                               .centerInside().get();
        bitmap = getResizedBitmap(bitmap,20);

        bitmap.compress(Bitmap.CompressFormat.PNG, 0, outStream);

        outStream.flush();
        outStream.close();
        // Save a file: path for use with ACTION_VIEW intents

        Log.i("file path before", mCurrentPhotoPath);

    } catch (Exception e) {
        Log.i("exception", e.toString());
    }
    return image;
}   

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);
}

The file size is 3 - 4 MB. I want max 600KB file.

ColdFire
  • 6,764
  • 6
  • 35
  • 51
sandy
  • 85
  • 8
  • You might wanna check this answer out. This is not same as your questions but this piece of code with resize, compress photo and even shows a sample code to upload the photo to server using retrofit https://stackoverflow.com/a/50017766/3136282 – Arshad Apr 27 '18 at 12:49

1 Answers1

0

I hope you should compress image to a Base 64 String then send to server as below code, you have to use your bitmap here.

Bitmap bitmap=/*intialize bitmap by your image's bitmap*/;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();

String encodedImage1 = Base64.encodeToString(byteArray, Base64.DEFAULT);

// encodedImage1 for passing to server

Thanks

ColdFire
  • 6,764
  • 6
  • 35
  • 51
Jitin
  • 1
  • 1