How to convert base64 data:url to link url? - java

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

Related

Use Floating Widget to take screenshot of any screen

I am trying to take a screenshot using Floating Widget. But I can't find any way of doing so. I searched for MediaProjection API but couldn't find anything helpful. Right now, If I tap the floating widget, it only captures the screenshot of the floating widget.
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Screenshot.java is my class for taking the screenshot
Bitmap bitmap = Screenshot.takescreenshotOfView(v);
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "DUOProfile" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "profilepic"+".jpg");
Toast.makeText(getApplicationContext(), "Picture saved in DUOProfile folder",Toast.LENGTH_SHORT).show();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error occured. Please try again later.",Toast.LENGTH_SHORT).show();
}
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
}
});
Screenshot.java
package com;
import android.graphics.Bitmap;
import android.view.View;
public class Screenshot {
public static Bitmap takescreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public static Bitmap takescreenshotOfView(View view) {
return takescreenshot(view.getRootView());
}
}
Pass the view in takescreenshotOfView method
Bitmap bitmap = takescreenshotOfView(view);
This will return bitmap image, just saved in your internal/sd card
public Bitmap takescreenshotOfView(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}

Set a bitmap image in ImageView

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!

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

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