Android string file to image - java

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

Related

PNG image from java server to android

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.

Which is the best way to upload multiple images to the server in android

I am using okHttp to upload multiple images(more than 10 in this case) to the server using multipartbody.
I and my friend had argument, I am saying to upload all images in a single request.
He is saying send one request at a time once the previous image is uploaded upload next one.
Which is the right thing to do, so the server works fast and no timeout occurs.
You can send Base64 format (String) like below and create one text file that contains all encoded photo as string
/**
* Encodes the image to Base64.
*/
private String encodeImage(String photoPath) {
File imagefile = new File(photoPath);
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, 80, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
and use MultipartUtility to upload file:
https://github.com/cloudinary/cloudinary_android/blob/master/Cloudinary/src/com/cloudinary/MultipartUtility.java

Decode base64 image and store on disk (using java) out of memory

i need to store on disk a base64 image but i have an error: "Out of memory" when i decode base64 image into byte[]. The size image is about 6MB
This is my code:
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(photo); //HERE I HAVE THE ERROR!!
log.debug("binary ok");
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
String nomeEdata = String.valueOf(Calendar.getInstance().getTimeInMillis() + ".jpg");
String nomeImg = resourceBundle.getString("schede.pathSaveImage") + nomeEdata;
File outputfile = new File(nomeImg);
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
Please, Any suggests?
You could write the "photo" content to a temporary file and then read from it using a Base64InputStream.
In the end, however, the BufferedImage will have the entire raw image in memory. This will require that you have a heap size large enough to accommodate this. You may just have to increase the Xmx value.
final BufferedImage bi = ImageIO.read(new Base64InputStream(new ReaderInputStream(new StringReader(photo), "ascii"));
final File file = ...
final FileOutputStream fos = new FileOutputStream(file);
try
{
ImageIO.write(bi, "png", new Base64OutputStream(fos));
}
finally
{
fos.close();
}
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReaderInputStream.html

I do not understand why BitmapFactory.decodeByteArray is returning null [duplicate]

In my application I am converting base64 string to image.For that I initially converted base 64 file to byte array and later am trying to convert to images.
To convert to Images I am using the below code
File sdImageMainDirectory = new File("/data/data/com.ayansys.Base64trial");
FileOutputStream fileOutputStream = null;
String nameFile="Images";
try {
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 5;
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
fileOutputStream = new FileOutputStream(
sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");
BufferedOutputStream bos = new BufferedOutputStream(
fileOutputStream);
myImage.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
but am getting my image as null at
Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
Please let me know your valuable suggestions.
Thanks in advance :)
decodeByteArray will not convert base 64 encoding to byte array. You need to use Base64 to byte array converter first
I ran into this same problem. I solved it by removing this part of the string:
"data:image/jpeg;base64,"

To read an image from Android Emulator

This is my code to convert image file into byte array.
public String GetQRCode() throws FileNotFoundException, IOException {
/*
* In this function the first part shows how to convert an image file to
* byte array. The second part of the code shows how to change byte array
* back to a image.
*/
AssetManager mgr = mAppView.getContext().getAssets();
InputStream in = mgr.open("www/Siemens_QR.jpg");
InputStreamReader isr = new InputStreamReader(in);
char[] buf = new char[20];
isr.read(buf, 0, 20);
isr.close();
// byte[] bytes = bos.toByteArray();
String abc = buf.toString();
return abc;
}
Here I am converting an image file into byte array. I am able to do this. But when try to read this image file using the path ("sdcard/Download/Siemens_QR.jpg") stored in emulator then I am getting VM aborting error. Please suggest me the correct path to read the image file stored in the emulator.
if you have jpg image stored on SD card then get the file path and try to convert the image to byte using following method...
Bitmap bitmap = BitmapFactory.decodeFile(file path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] byte_img_data = baos.toByteArray();

Categories

Resources