Set a bitmap image in ImageView - java

I've tried this
try {
byte[] decodedString = Base64.decode(repPlus, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.imageView.setImageBitmap(decodedByte);
} catch (Exception e) {
Log.d("Error: ", e.getMessage());
}
And it returns an error:
bad base-64
And then I've tried this Bad base-64 error. And it removes the error. And Base64 to Bitmap to display in ImageView for decoding a base64 String
try {
String repSlash = product.getImage().replace("/", "_");
String repPlus = repSlash.replace("+", "-");
byte[] decodedString = Base64.decode(repPlus, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.imageView.setImageBitmap(decodedByte);
} catch (Exception e) {
Log.d("Error: ", e.getMessage());
}
But the image does not views in the application.

Try doing this after initializing the Bitmap decodedByte
BitmapDrawable drawable = new BitmapDrawable(getResources(), decodedByte);
holder.imageView.setBackgroundDrawable(drawable);
EDIT: Try this:
String base64Image = product.getImage().split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.imageView.setImageBitmap(decodedByte);
Hope this helped!

Related

How to convert base64 data:url to link url?

example I have url : data:image/png;base64,ajshgvdkau....
I want to convert it to : http://example.com/pic.png
is there any code to do this in java android ?
==================================
Edit 1
I'm trying to put the image from url and display it to textview. when i use case 2, the image display perfectly,
but in case 1 not. there is error "unknown protocol: data" and "W/AwContents: nativeOnDraw failed; clearing to background color"
//case 1
// String base_url = "<p>Image 1 : <img src=\"data:image/jpeg;base64,/9j/4AAQSk...
//case 2
String base_url = "<p>Image 1 : <img src=\"http://example.com/android/tryout/logo.png\"></img></p>";
Spanned span2 = Html.fromHtml(base_url,getImageHTML(),null);
TextView tv = (TextView)findViewById(R.id.target);
tv.setText(span2);
and this is my function
public Html.ImageGetter getImageHTML() {
Html.ImageGetter imageGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
try {
Drawable drawable = Drawable.createFromStream(new URL(source).openStream(), "src");
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
} catch(IOException exception) {
Log.v("IOException", exception.getMessage());
return null;
}
}
};
return imageGetter;
}
Thanks for the answer.
you can use Base64 class to decode the encoded string as byte array https://developer.android.com/reference/android/util/Base64.html
byte[] decodedString = Base64.decode(encodedUrl, Base64.DEFAULT);
and then you can create bitmap from the byte array.
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
please make sure to remove meta info (ie. data:image/png;base64,) when decode the url.
UPDATE:
here sample based on your code:
public Html.ImageGetter getImageHTML() {
Html.ImageGetter imageGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
try {
String base64Image = source.substring("data:image/jpeg;base64,".length);
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable drawable = new BitmapDrawable(getActivity().getResources()/*or other way to get resource reference*/, bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
} catch(IOException exception) {
Log.v("IOException", exception.getMessage());
return null;
}
}
};
return imageGetter;
}
I have solved this problem. I'm using Base64InputStream. Delete "data:image/jpeg;base64," first to get valid base64 code.
public Html.ImageGetter getImageHTML() {
Html.ImageGetter imageGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
try {
String[] str = source.split("base64");
Base64InputStream is = new Base64InputStream(new ByteArrayInputStream(str[1].getBytes()), 0);
Bitmap decodedByte = BitmapFactory.decodeStream(is);
Drawable drawable = new BitmapDrawable(getResources(), decodedByte);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}catch(Exception e){
e.getMessage();
return null;
}
}
};
return imageGetter;
}

Bitmap - Base64 String - Bitmap conversion android

I am encoding an image in the following way and store it in my database:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Now I am trying to decode it in the following way and display it in an ImageView :
try{
InputStream stream = new ByteArrayInputStream(image.getBytes());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
catch (Exception e) {
return null;
}
}
However the ImageView remains blank and the image is not displayed. Am I missing something?
Try decoding the string first from Base64.
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
In you case:
try{
byte[] decodedByte = Base64.decode(input, 0);
InputStream stream = new ByteArrayInputStream(decodedByte);
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
catch (Exception e) {
return null;
}

set image button - uri, android

My program generates several display keys, and I would like to assign each icon. The assets hold icon. But android does not load icons
button.setText(shop.getName());
Drawable icon;
int s = shop.getId();
String sk = Integer.toString(s);
String imageUri = "file:///android_asset/shop"+sk+".png";
Log.w("imageURI", imageUri);
Uri uri=Uri.parse(imageUri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
icon = Drawable.createFromStream(inputStream, uri.toString() );
} catch (FileNotFoundException e) {
icon = getResources().getDrawable(R.drawable.shopping1);
}
Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));
button.setCompoundDrawablesWithIntrinsicBounds( null, d, null, null );
Log: ... file:///android_asset/shop1.png
Try this:
button.setText(shop.getName());
Drawable icon;
int s = shop.getId();
String sk = Integer.toString(s);
String imageUri = "file:///android_asset/shop"+sk+".png";
Log.w("imageURI", imageUri);
Uri uri=Uri.parse(imageUri);
InputStream is;
try {
is = this.getContentResolver().openInputStream( uri );
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 10;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);
Drawable icon = new BitmapDrawable(getResources(),preview_bitmap);
} catch (FileNotFoundException e) {
//set default image from the button
icon = getResources().getDrawable(R.drawable.shopping1);
}
button.setBackground(icon);

Dynamically adding Thumbnail in android

i am trying to add a thumbnail dynamically to my relative layout. This is code here
public void showViewOfReceipt(String fileName)
{
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width/height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)(THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
ImageView image = new ImageView(this);
image.setImageBitmap(imageBitmap);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.expLayout5);
layout.addView(image);
}
catch(Exception ex) {
}
}
It never shows anything
Regards
Change your following line of code,
catch(Exception ex)
{
}
to,
catch(Exception ex)
{
e.printStack();
}
So, you will get error , if any.
1- Change your relative layout to Linear Layout
2- Use this code below to get the bitmap image
Uri photoUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
if (cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap imageReturned = BitmapFactory.decodeFile(filePath);
showImageInLayout(imageReturned);
Then define a function showImageInLayout(Bitmap imageReturned)
public void showViewOfReceiptInLayout(Bitmap imageBitmap)
{
byte[] imageData = null;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, yourWidth, yourHeight, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
ImageView image = new ImageView(this);
image.setImageBitmap(imageBitmap);
layout.addView(image);
}
Comment code line:
//image = (ImageView) findViewById(R.id.imageView1);
Please update the Question with the error or exception log code so we can help you properly.
And as per Altaaf answer its an error in the fileName. So Please check it or give the code what you pass in it.
Thanks.

Decoding qr code from image stored on the phone with Zxing (on Android phone)

I have an app that receives qr code from the server. I want to decode it (not with intent and camera) and display the text it contains in my app. I have alredy done this in Java SE with jars from zxing with this code:
private class QRCodeDecoder {
public String decode(File imageFile) {
BufferedImage image;
try {
image = ImageIO.read(imageFile);
} catch (IOException e1) {
return "io outch";
}
// creating luminance source
LuminanceSource lumSource = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
// barcode decoding
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
return "reader error";
}
return result.getText();
}
}
But on Android, BufferedImage is not found.
Has anyone decoded qr code on android from image stored on the phone?
Tnx.
In android,you can do it this way:
#Override
protected Result doInBackground(Void... params)
{
try
{
InputStream inputStream = activity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null)
{
Log.e(TAG, "uri is not a bitmap," + uri.toString());
return null;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try
{
Result result = reader.decode(bBitmap);
return result;
}
catch (NotFoundException e)
{
Log.e(TAG, "decode exception", e);
return null;
}
}
catch (FileNotFoundException e)
{
Log.e(TAG, "can not open file" + uri.toString(), e);
return null;
}
}
Download ZXing from google code, and this class file: ZXing-1.6/zxing-1.6/androidtest/src/com/google/zxing/client/androidtest/RGBLuminanceSource.java can help you.
Quickmark and qr droid actually reads out what the code says, and you can decode barcodes saved on your phone. Hit the menu button when your load the image and select share, find decode qr droid or decode quickmark, and the'll do the magic. I prefer quickmark for reading codes, because it tells me what is typed in the code.

Categories

Resources