Bitmap - Base64 String - Bitmap conversion android - java

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

Related

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!

BitmapFactory.decodeStream returns null values while download image

We are using below function to download image from the URL. Sometimes BitmapFactory.decodeStream we are getting as null. Due to that issue , Notification are receiving without Image. Any one help us to resolve that issue..
This is my code:
private Bitmap getImageBitmap(String url)
{
Bitmap bmsd = null;
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bmsd = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bmsd;
}
try like this, if bitmap size is too high we need to resize the bitmap.
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}

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

How to convert Uri image into Base64?

I have write code to convert image from file location into base64. I can easily convert image into base64 from absolute file location like: C:/Users/Java Engineer/Desktop/test/gallery/magar/Kanuglam.jpg , but I can not convert from location like
. I want to convert image to use in android from web-service.
Here is code sample :
/**
* TEST JSON
*/
String convertToJsonArrayWithImageForMovieDetailTest(ResultSet rs) {
System.out.println("I am insied json converter");
JSONArray list = new JSONArray();
JSONObject obj ;
//File file;
File locatedFile;
FileInputStream fileInputStream;
try {
while (rs.next()) {
obj = new JSONObject();
System.out.println("inside RS");
System.out.println("date is there ha ha ");
obj.put("movie_name", rs.getString("name"));
obj.put("movie_gener", rs.getString("type"));
String is_free_stuff = rs.getString("is_free_stuff");
if (is_free_stuff == "no") {
is_free_stuff = "PAID";
} else {
is_free_stuff = "FREE";
}
obj.put("movie_type", is_free_stuff);
//String movie_image = rs.getString("preview_image");
//this does not work
String movie_image = "http://www.hamropan.com/stores/slider/2016-09-10-852311027.jpg";
//this works for me
// file = new File("C:/Users/Java Engineer/Desktop/Nike Zoom Basketball.jpg");
locatedFile = new File(movie_image);
// Reading a Image file from file system
fileInputStream = new FileInputStream(locatedFile);
if (locatedFile == null) {
obj.put("movie_image", "NULL");
} else {
byte[] iarray = new byte[(int) locatedFile.length()];
fileInputStream.read(iarray);
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(iarray);
String imageString = new String(img64);
obj.put("movie_image", imageString);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list.toString();
}
this block of code works for me but it seem slow
public String imageConvertMethod(String url) throws Exception{
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream input = new URL(url).openStream()) {
byte[] buffer = new byte[512];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
byte [] byte_array = output.toByteArray();
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(byte_array);
String imageString = new String(img64);
return imageString;
}
Ok, try this
bitmap = getBitmapFromUrl(image_url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] array = stream.getByteArray();
encoded_string = Base64.encodeToString(array, 0);
Method wo load image from url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#thanks to Fabio Venturi Pastor
Try this:
ImageUri to Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
}
}
Encode Bitmap in base64
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
Encode from FilePath to base64
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
output:
reference :
Take picture and convert to Base64

Converting images to bytes array

I just want to ask, I have an application like Meme Generator.
So after taking a picture, the picture will be send to second activity,
My question is that, I'm having Incompatible types on Second Activity Like
Required byte
found java.lang.object
can you help me? or suggest another kind of method for doing this?
First Activity:
FileIOManager fiom = new FileIOManager(this);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byteArray = stream.toByteArray();
fiom.write("name",byteArray);
FileIOManager Class:
public class FileIOManager {
private Context context;
public FileIOManager(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public void write(String filename, Object file) {
try {
FileOutputStream fos = context.openFileOutput(filename,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(file);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object read(String filename) {
Object object = null;
try {
FileInputStream fis = context.openFileInput(filename);
ObjectInputStream is = new ObjectInputStream(fis);
object = is.readObject();
is.close();
} catch (FileNotFoundException e) {
} catch (StreamCorruptedException e) {
} catch (IOException e) {
} catch (ClassNotFoundException e) {
}
return object;
}
and lastly Second Activity
imageView = (ImageView) findViewById(R.id.imageView2);
//byte[] byteArray = fiom.read("name");
byte[] byteArray = fiom.read("name");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageView.setImageBitmap(bmp);
Try this one, hope it will help...
public byte[] bitmapToByteArray(Bitmap bitmap)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] bitmapBytes = bitmapToByteArray(bmp);

Categories

Resources