Share an image using a memory stream or byte array - java

I have some standard code to share an image in my Android app. The image exists on the storage and I provide an URI to the image. This all works fine.
However, this requires the WRITE_EXTERNAL_STORAGE permission. Is there a way I can share an image without the need of this permission, for example, to not save the image to storage, but specifying a memory stream or byte array?
Thanks!

You can convert an image file to a byte array with the following code, which I taken from an answer to a similar question: How to convert image into byte array and byte array to base64 String in android?
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
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();
Optional step to encode in Base64
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Related

Bitmap cannot properly decode the byteArray which represents data from a file

I've the following code:
File file = new File(filepath);
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeByteArray(fileData,0, fileData.length);
I succesfully manage to fill fileData with bytes, although to be honest I think there are too few bytes to represent the content of the jpg file referenced by filepath. But as even if I set it to have more bytes they are left as 0, I guess it contains the proper bytes.
But once the last instruction is executed bm is left as null.
What could I do so I can properly get the bitmap from that data?
PD: I'm aware it would be more logical to do:
Bitmap bm = BitmapFactory.decodeFile(filePath);
But, for some reason, that also returns null, so I'm taking this less direct approach to try to solve the issue.
After some investigation, I've checked that problem is that just a few bytes are the one being retrieved, with that, it's no brainer bitmpa ends up being null, what could I do so I get all bytes?

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

Java - GIF to base64 string

how to convert gif to base64?
here's what i try so far
public static String convertImageToBase64(String urlString, String type ){
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
URL url = new URL(urlString);
BufferedImage img = ImageIO.read( url );
ImageIO.write(img, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
code above is working, but it lost the animation
Most likely the class BufferedImage does not support images with animation. So the code opens and parses the image only to the first frame.
Instead try directly getting the bytes with URL.openStream and then just convert the downloaded bytes to base64.
Notice that this way you can't be sure that the downloaded file is actually an image since you are not opening it at all. This may or may not be needed.
You have to use
public String encodeToString(byte[] src)
of class BASE64.Encoder (from java 8)
I'm assuming what you want is a Base64 representation of the GIF file itself, not the ImageIO representation. If you have an older version of Java without built-in Base64 support, Apache Commons Codec will do the job. Read the file into a byte array using URL.openStream(), not with ImageIO, then call Base64.encodeBase64String. If you want the result URL encoded, call Base64.encodeBase64URLSafe instead.
If you actually want the ImageIO representation, then you're stuck with losing the animation.

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

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