Convert Base64 String To Image In Android
I have converted an image into base64 through an online site. I went through this link to hold base64 string in a String. But i get an error saying Error:(38, 36) error: consta
Solution 1:
You can just basically revert your code using some other built-in methods.
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
BitmapdecodedByte= BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Solution 2:
//encode image(from image path) to base64 stringByteArrayOutputStreambaos=newByteArrayOutputStream();
Bitmapbitmap= BitmapFactory.decodeFile(pathOfYourImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StringimageString= Base64.encodeToString(imageBytes, Base64.DEFAULT);
//encode image(image from drawable) to base64 stringByteArrayOutputStreambaos=newByteArrayOutputStream();
Bitmapbitmap= BitmapFactory.decodeResource(getResources(), R.drawable.yourDrawableImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StringimageString= Base64.encodeToString(imageBytes, Base64.DEFAULT);
Solution 3:
Did you try to use the class BitmapFactory ?
Please try something like this :
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
BitmapdecodedByte= BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Also, according to the error you get, it seems that you use a static final String to hold you encoded base64 string. In Java, the length of constant string is limited to 64k.
Solution 4:
First of all check your string
http://codebeautify.org/base64-to-image-converter
Try this way to convert.
publicclassMainActivityextendsAppCompatActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageViewimage=(ImageView)findViewById(R.id.image);
//encode image to base64 stringByteArrayOutputStreambaos=newByteArrayOutputStream();
Bitmapbitmap= BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StringimageString= Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
BitmapdecodedImage= BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
}
}
Post a Comment for "Convert Base64 String To Image In Android"