Try this, first scale your image to the required width and height, just pass the original bitmap, the required width and the required height for the following method and get a scaled bitmap as a result:
For example: Bitmap scaledBitmap = getScaledBitmap (originalBitmap, 250, 350);
private Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight) { int bWidth = b.getWidth(); int bHeight = b.getHeight(); int nWidth = bWidth; int nHeight = bHeight; if(nWidth > reqWidth) { int ratio = bWidth / reqWidth; if(ratio > 0) { nWidth = reqWidth; nHeight = bHeight / ratio; } } if(nHeight > reqHeight) { int ratio = bHeight / reqHeight; if(ratio > 0) { nHeight = reqHeight; nWidth = bWidth / ratio; } } return Bitmap.createScaledBitmap(b, nWidth, nHeight, true); }
Now just pass the scaled bitmap to the following method and return the base64 string:
For example: String base64String = getBase64String (scaledBitmap);
private String getBase64String(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP); return base64String; }
To decode a base64 string back to a bitmap:
byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP); Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);
Ashwin Jun 08 '17 at 10:44 on 2017-06-08 10:44
source share