I am new to android. I have created one app to upload an image to server. It works perfectly for small size images but for larger images(>1 MB), this does not work. Here is
For compressing an image use this library that is on GitHub (reduce size):
https://github.com/zetbaitsu/Compressor
Encode to base64:
public String encodeBase64(Bitmap image){
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}
Send base64 String to server via volley request (Post or Get method):
https://developer.android.com/training/volley/simple.html
You need to do this man:
1: Get Image and check size. For example: if fileSize<=1MB
2: ShrinkBitmap (So that large image won't cause memory issues. See ShrinkBitmap() below.
3: If you want to Encode to base64 or else then you can do it and compress to 100%. See Encodetobase64() below
4: Send to Server
public Bitmap ShrinkBitmap(String file, int width, int height)
{
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if(heightRatio > 1 || widthRatio > 1)
{
if(heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
}
else
{
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
public String encodeTobase64(Bitmap image)
{
String byteImage = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
try
{
System.gc();
byteImage = Base64.encodeToString(b, Base64.DEFAULT);
}
catch (Exception e)
{
e.printStackTrace();
}
catch (OutOfMemoryError e)
{
baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
b = baos.toByteArray();
byteImage = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("Bitmap", "Out of memory error catched");
}
return byteImage;
}
This encoding function is compressing bitmap also.
Goodluck!!
In my app too i face this problem.what i have done was, i uploaded the images and set that to imageview and i gave static height and width to be 300*300. and saved the bitmap in server.
bitmap = Bitmap.createScaledBitmap(bitmap,desiredImageWidth,desiredImageHeight,true);
sace this in server. here desiredImageWidth, desiredImageHeight are static values.