I'm trying to send multiple PNG:s to an adroid-phone.
(Every image is sent in a separate JSON-object together with multiple other objects that is associated with the image.)
I'm sending the images as byte-arrays and my phone is receiving them.
The problem starts when I try to decode with BitmapFactory.decodeByteArray which returns null.
How should I encode on the server-side and decode on the android-side?
First attempt on server-side:
File imgPath = new File(path);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] bytes = data.getData();
Second attempt on server-side:
byte[] bytes = null;
File file = new File(path);
bytes = Files.readAllBytes(file.toPath());
Android-side:
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
Sending JSON from server:
public class Response {
List<Person> mPeople;
..other objects...
}
public class Person {
String name;
String image; //base68string
}
public ServerThread {
Response resp = create objects to send;
String str = new Gson().toJson(resp);
OutputStreamWriter.write(str);
}
Receiving JSON on Android-side:
Response resp = gson.fromJson(str, Response.class);
List<Person> = resp.getPersons();
//Person-class on the android side is Parcable
So I tried this approach but it still doesn't work:
// Server-side
import java.util.Base64;
import java.util.Base64.Encoder;
File file = new File(path);
byte[] bytes = Files.readAllBytes(file.toPath());
Encoder e = Base64.getEncoder();
String base64String = e.encodeToString(bytes);
//Android-side
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
I suggest you to try Picasso or Glide to load image into imageview directly from the URL. You don't have to manage this all stuff manually.
I was doing that stuff but after using one of this library it removes lots of work.
Just try this.
Related
These are my encoding and decoding methods.
public String encodeBase64(Bitmap bit){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bit.compress(Bitmap.CompressFormat.PNG, 100, baos); // Could be Bitmap.CompressFormat.PNG or Bitmap.CompressFormat.WEBP
byte[] bai = baos.toByteArray();
return Base64.encodeToString(bai, Base64.DEFAULT);
}
public Bitmap decodeBase64(String base64Image){
byte[] data = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap bm;
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
return bm;
}
This is encoded data from a bitmap
iVBORw0KGgoAAAANSUhEUgAABLAAAAdcCAYAAAC7T3KrAAAABHNCSVQICAgIfAhkiAAAIABJREFU
eJzswQEBAAAAgJD+r+4ICgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... etc
But the data i get from the server looks like this
{"type":"Buffer","data":[105,86,66,79,82,119,48,75,71,103,111,65,65,65,... etc
I can get pure data or the type and data json object. Ive tried to decode both. When i try to decode with the type and data it gives me a null bitmap, when i decode the raw data only the image is not displayed, but nothing seems to crash.
Do i need to retrive all those array numbers and convert them to chars before decoding? Ive read other post and it sounded very straigtforward, just encode and then decode.
decode base_64 string Imgae in codigneter
$
aadharcard_front = image name(database)
if(!empty($aadharcard_front))
{
$aadharcard_front = base64_decode($aadharcard_front);
$aadharcard_front_time = time().'.png';
file_put_contents(APPPATH.'../media/uploads/'.$aadharcard_front_time,$aadharcard_front);
$user_data['aadharcard_front'] = $aadharcard_front_time;
}
In Java server I fetch image from external service URL like:
InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
Then on Android I parse it like:
byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
Result: Image not displayed, ain't errors/exceptions neither on server nor on client.
What is the problem here?
EDIT: On android I use class android.util.Base64
Thanks,
Use Picasso library to load image:
You just need to add 1 line of code to show the image on ImageView
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
You can learn more from here
use this to convert to base 64
public static String uploadPic(Bitmap bm) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = ""+ Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
check if image is uploaded then using volley String request object download the string response using this code convert it back.
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
As commented, let's assume base64Content is the base64 string responsed from your web service/server-side app, you can refer to the following sample code:
String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Moreover, if your server compressed reponse data either by gzip or deflate, your client app must decompress the data first.
Hope this helps!
from server side an image is being sent to me.
The image i receive it as string, what server side is sending me is the entire file.
How can I read it in android side?
File tempFile = File.createTempFile("image", ".jpg", null);
// tempFile.wr
byte[] bytes = output.toString().getBytes();
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bytes);
output is the result i receive, its string which is the entire file send from server side.
Bitmap myBitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath());
m2.setImageBitmap(myBitmap);
I am getting SkImageDecoder::Factory returned null
this code running produces this log cat
File tempFile = File.createTempFile("image", ".jpg", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(output.toString().getBytes());
fos.close();
System.out.println(""+tempFile.getAbsolutePath());
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath());
m2.setImageBitmap(bitmap);
http://www.speedyshare.com/8BdVs/log.txt
Here is the code to convert into stream from base64 decoded string of image. This will only work if it has properly encoded in Base64 and stored it in your server
Bitmap img = null;
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
img = BitmapFactory.decodeStream(stream);
I want to use an existing instance of WebClient to download an image. The reason for this is because I want the cookies to be passed with the request.
How can I download an image using an existing instance of WebClient?
Also, how can I base64 encode the image to be able to view it using data:image/jpeg;base64,...
Current code:
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
UnexpectedPage imagePage = client.getPage("http://...");
String imageString = imagePage.getWebResponse().getContentAsString();
BASE64Encoder encoder = new BASE64Encoder();
String base64data = encoder.encode(imageString.getBytes());
So now I have base64 data of the image, but I still can't view the image using data:image/jpeg;base64,....
A couple of things to consider:
The BASE64Encoder() generates a string that has a line break every 77 chars. Take that out using .replaceAll("\r?\n","").
For that method also, it is better to retrieve the web page InputStream rather than the string. Also, to convert that to a byte array, I used a utility method (source and other options can be found here).
Working source code:
public static void main (String args[]) throws IOException {
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
UnexpectedPage imagePage = client.getPage("http://i.stack.imgur.com/9DdHc.jpg");
BASE64Encoder encoder = new BASE64Encoder();
String base64data = encoder.encode(inputStreamToByteArray(imagePage.getWebResponse().getContentAsStream()));
System.out.println("<img src=\"data:image/png;base64,"+base64data.replaceAll("\r?\n","")+"\" />");
}
private static byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
Source image:
Output base64 image here.
I have a .net ASMX webservice that I'm consuming using the ksoap2 library. In the service, I first save the user image and later retrieve it. However, once I retrieve it, the byte array is intact, but the BitmapFactory is unable to decode it and returns a null.
To convert to byte array:
Bitmap viewBitmap = Bitmap.createBitmap(imageView.getWidth(),
imageView.getHeight(), Bitmap.Config.ARGB_8888);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
viewBitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
The webservice accepts the bytearray in the byte[] format.
To convert the array into bitmap:
byte[] blob= info.get(Main.KEY_THUMB_BYTES).getBytes();
Bitmap bmp=BitmapFactory.decodeByteArray(blob,0,blob.length); // Return null :(
imageView.setImageBitmap(bmp);
From partial-analysis, it appears that the byte array does not change. Then why does decoding return null? Is there a better to save an image and pass it through a webservice? I didn't analyze the whole byte array, so I'm guessing it might've changed a bit.
Any thoughts? Many thanks!
UPDATE:
I just tried converting the byte[] to string using:
Base64.encodeToString( bos.toByteArray(), Base64.DEFAULT);
And decode using:
byte[] blob= Base64.decode(info.get(Main.KEY_THUMB_BYTES));
Now all i get is a White picture. I'm not sure what's wrong here. Please help.
UPDATE:
I'm storing this image inside of a database, in a column of type varchar(max). Should I be storing this byte array string inside a different sql data type? I'm not too experienced with SQL, so I used varchar because it did not convert text to unicode, which I thought might be good for thie byte array.
Thanks!
convert your byte arrays to Base64 that is a string and easy to transfer:
public static String bitmapToBase64(Bitmap bitmap) {
byte[] bitmapdata = bitmapToByteArray(bitmap);
return Base64.encodeBytes(bitmapdata);
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
and
public static Bitmap base64ToBitmap(String strBase64) throws IOException {
byte[] bitmapdata = Base64.decode(strBase64);
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0,
bitmapdata.length);
return bitmap;
}
also you can do it not only on image files but also on every file types:
public static String fileToBase64(String path) throws IOException {
byte[] bytes = fileToByteArray(path);
return Base64.encodeBytes(bytes);
}
public static byte[] fileToByteArray(String path) throws IOException {
File imagefile = new File(path);
byte[] data = new byte[(int) imagefile.length()];
FileInputStream fis = new FileInputStream(imagefile);
fis.read(data);
fis.close();
return data;
}
public static void base64ToFile(String path, String strBase64)
throws IOException {
byte[] bytes = Base64.decode(strBase64);
byteArrayTofile(path, bytes);
}
public static void byteArrayTofile(String path, byte[] bytes)
throws IOException {
File imagefile = new File(path);
File dir = new File(imagefile.getParent());
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(imagefile);
fos.write(bytes);
fos.close();
}