I would like send bitmap from activity to class, but without using static methods, or shared preference, any ideas?
You can solve your problem by do something like that: Hope it will help !
Write Method to encode your bitmap into string base64-
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
Pass your bitmap inside this method like something in your preference:
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeTobase64(yourbitmap));
editor.commit();
And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Please pass your string inside this method and do what you want.
Related
how can I save an ImageView in sharedpreferences?
I am trying to create a quiz where the player needs coins to unlock the next level, so the next level will be with a lock, and as soon as the player buys the level, the lock goes away, I already got the score. save, now only the image is missing, thanks in advance everyone!
solved your problem do something like that:
Write Method to encode your bitmap into string base64-
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
ret
urn imageEncoded;
}
2.Pass your bitmap inside this method like something in your preference:
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeTobase64(yourbitmap));
editor.commit();
3 And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Please pass your string inside this method and do what you want.
Get bitmap from the imageview then convert into base64 string then save it to the sharedpreference then again when you need the image get the base64 string convert to bitmap then user imageview.setBitmap(bitmap);
Now You are all set
For encoding and decoding bitmap you can use this, :
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
It isn't a good idea to store your images in shared preferences because shared preferences are used for storing app settings that are lightweight. You should use an SQLite or Room database especially if you have many images. Another way is to cache your images in external storage.
I have a Base64 String that represents a BitMap image.
I need to transform that String into a BitMap image again to use it on a ImageView in my Android app
How to do it?
This is the code that I use to transform the image into the base64 String:
//proceso de transformar la imagen BitMap en un String:
//android:src="c:\logo.png"
Resources r = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
//String encodedImage = Base64.encode(b, Base64.DEFAULT);
encodedImage = Base64.encodeBytes(b);
You can just basically revert your code using some other built in methods.
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
To anyone who is still interested in this question:
If:
1-decodeByteArray returns null
2-Base64.decode throws bad-base64 Exception
Here is the solution:
-You should consider the value sent to you from API is Base64 Encoded and should be decoded first in order to cast it to a Bitmap object!
-Take a look at your Base64 encoded String, If it starts with
data:image/jpg;base64
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:
final String encodedString = "data:image/jpg;base64, ....";
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",") + 1);
Now the pureBase64Encoded object is ready to be decoded:
final byte[] decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Now just simply use the line below to turn this into a Bitmap Object! :
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0,
decodedBytes.length);
Or if you're using the great library Glide:
Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);
This should do the job! It wasted one day on this and came up to this solution!
Note:
If you are still getting bad-base64 error consider other Base64.decode flags like Base64.URL_SAFE and so on
This is a very old thread but thought to share this answer as it took lot of my development time to manage NULL return of BitmapFactory.decodeByteArray() as #Anirudh has faced.
If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULT
byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
To check online you can use
http://codebeautify.org/base64-to-image-converter
You can convert string to image like this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image =(ImageView)findViewById(R.id.image);
//encode image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
}
}
http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html
This is a great sample:
String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);
Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af
This is the only code that worked for me in the past.
I've found this easy solution
To convert from bitmap to Base64 use this method.
private String convertBitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
To convert from Base64 to bitmap OR revert.
private Bitmap convertBase64ToBitmap(String b64) {
byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}
In Kotlin you can use extension function as bellow:
fun String.base64ToByteCode() = Base64.decode(this.substring(this.indexOf(",") + 1), Base64.DEFAULT)
and call it as bellow:
yourBase64String.base64ToByteCode()
This solution is working fine for me. if you receive null please let me know.
private void bytesToImage(ImageView imageView, String base64String) {
if (!base64String.isEmpty()) {
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Glide.with(this).load(decodedByte).into(imageView);
}
I have tried all the solutions and this one worked for me
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage
I have a Base64 string image .I want to convert it into blob type and save it in database..
I have
String base64Image="iVBORw0KGgoAAAANSUhEUgAAAGAAAACgCAYAAADzcGmMAAAACSV...";
This is what I tried..
byte[] byteImage=org.apache.commons.codec.binary.Base64.decodeBase64(befImage.getBytes());
json.put("during_unloading_photo", byteImage);
where json is my JSONObject and
during_unloading_photo is the column name which is blob type.
for saving blob into DataBase you have to convert your base64 satring image to Byte[] and then you can save byte[] into db.
for converting base64 stringto bitmap
public static Bitmap decodeBase64Profile(String input) {
Bitmap bitmap = null;
if (input != null) {
byte[] decodedByte = Base64.decode(input, 0);
bitmap = BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
return bitmap;
}
and now you can convert this Bitmap to Byte[] Like:
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
return null;
}
then finally you can save this Byte[] to Db.make sure your column name have type with blob
enjoy your code:)-
getBytes gives you the bytes of the string, it does not do base64 decoding. You will need to use a Base64 decoder to do the conversion. A little search will show up several options you can use.
I have an Android application which sends an image to a web service. I want to send the same photo back from the web service to Android.
I made a test program to compare the base64 data that's sent from Android to the server and the base64 that's sent back from server to Android -- they are exactly equal.
I want to use the base 64 string to create a bitmap, so I tried this:
String image = client1.getBaseURI("restaurantFoods/OneFood/"
+ this.getID() + "/getImage");
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
if(decodedByte == null){
Log.d(this.getFoodItem().getName(), image);
Log.d("isNull", "Yes");
}
else{
Log.d("isNull", "No");}
I keep getting null because the log just prints "YES".
Can anyone please help?
If you want to know how I encode the image it is as follows:
private String getBase64(Bitmap bitmap) {
String imgString = Base64.encodeToString(getBytesFromBitmap(bitmap),
Base64.NO_WRAP);
return imgString;
}
private byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
R.drawable.pizza);
String iconBase64 = this.getBase64(icon);
Try this to bitmap;
public Bitmap convert(String img){
byte[] b = Base64.decode(img, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
And this to String
public String convert(Bitmap bm, int quality){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] byt = baos.toByteArray();
bm.recycle();
return Base64.encodeToString(byt, Base64.DEFAULT);
}
Really I don't see any real problems with your code, but these have worked for me so I suggest that you try them and see if that is actually your problem.
I have a Base64 String that represents a BitMap image.
I need to transform that String into a BitMap image again to use it on a ImageView in my Android app
How to do it?
This is the code that I use to transform the image into the base64 String:
//proceso de transformar la imagen BitMap en un String:
//android:src="c:\logo.png"
Resources r = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
//String encodedImage = Base64.encode(b, Base64.DEFAULT);
encodedImage = Base64.encodeBytes(b);
You can just basically revert your code using some other built in methods.
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
To anyone who is still interested in this question:
If:
1-decodeByteArray returns null
2-Base64.decode throws bad-base64 Exception
Here is the solution:
-You should consider the value sent to you from API is Base64 Encoded and should be decoded first in order to cast it to a Bitmap object!
-Take a look at your Base64 encoded String, If it starts with
data:image/jpg;base64
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:
final String encodedString = "data:image/jpg;base64, ....";
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",") + 1);
Now the pureBase64Encoded object is ready to be decoded:
final byte[] decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Now just simply use the line below to turn this into a Bitmap Object! :
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0,
decodedBytes.length);
Or if you're using the great library Glide:
Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);
This should do the job! It wasted one day on this and came up to this solution!
Note:
If you are still getting bad-base64 error consider other Base64.decode flags like Base64.URL_SAFE and so on
This is a very old thread but thought to share this answer as it took lot of my development time to manage NULL return of BitmapFactory.decodeByteArray() as #Anirudh has faced.
If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULT
byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
To check online you can use
http://codebeautify.org/base64-to-image-converter
You can convert string to image like this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image =(ImageView)findViewById(R.id.image);
//encode image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
}
}
http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html
This is a great sample:
String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);
Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af
This is the only code that worked for me in the past.
I've found this easy solution
To convert from bitmap to Base64 use this method.
private String convertBitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
To convert from Base64 to bitmap OR revert.
private Bitmap convertBase64ToBitmap(String b64) {
byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}
In Kotlin you can use extension function as bellow:
fun String.base64ToByteCode() = Base64.decode(this.substring(this.indexOf(",") + 1), Base64.DEFAULT)
and call it as bellow:
yourBase64String.base64ToByteCode()
This solution is working fine for me. if you receive null please let me know.
private void bytesToImage(ImageView imageView, String base64String) {
if (!base64String.isEmpty()) {
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Glide.with(this).load(decodedByte).into(imageView);
}
I have tried all the solutions and this one worked for me
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage