How to convert Image to String and vice versa in java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
How to convert Image to String and vice versa in java.
I convert a file.jpg to byte array and then convert byte array to String, but when I reconvert the result String to Image, I got error
Here is code
public void StringToFile( String s1, String filename ) {
byte[] byte02 = s1.getBytes( );
//byte[] byte02 = s1.getBytes( StandardCharsets.UTF_8 );
try {
System.out.println( "Data is corrupted when converting image "
+ "file to String and vice versa, this function is just a test" );
FileOutputStream output = new FileOutputStream( filename );
output.write( byte02 );
output.close();
ByteArrayInputStream bis = new ByteArrayInputStream( byte02 );
BufferedImage bImage2 = ImageIO.read( bis );
ImageIO.write( bImage2, "jpg", new File( filename ) );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() );
}
}

It can cause problems when you convert binary data into an regular string.
The reason is that converting a byte array into an String converts the bytes into characters using the character encoding of the system. Bytes that have no character mapped to it will be lost or modified in the process.
Instead I'd suggest you use
java.util.Base64.getEncoder().encodeToString(byte[])
to convert the file's bytes into a string value and
java.util.Base64.getDecoder().decode(String)
to get the value back into bytes.

If possible, avoid converting binary data like a graphics file to String. String is meant to contain a sequence of Unicode characters, and not arbitrary data. If you need to transform binary data into printable characters, use the approach given in the the answer by Roland Kreuzer, namely an encoding like base 64.
On Android, to convert a Bitmap to byte[], you can use the Bitmap.compress method:
import android.graphics.Bitmap;
private byte[] getBytesFromImage (Bitmap image) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
This method returns a byte[] array which you can use to store the image in your Database, for instance, as a Blob value.
To convert the byte[] to an Image, use the BitmapFactory.decodeByteArray method:
BitmapFactory.decodeByteArrray(imageBytes, 0, imageBytes.length); // imageBytes is the byte[] array of the image that was returned by the getBytesFromImage method.

Related

How to convert Bytes Array to a String in order to see it printed onto the console?

I am trying to convert a Byte Array to a String in order to be able to see this Vector/Array and analyse how these bytes are organized.
I'm using the code below to do it:
byte[] bytes = bos.toByteArray();
String msgDecode = new String(bytes); // trying to convert byte in String
System.out.println("Vetor de bytes [" + msgDecode + "]"); // Showing it
But it's not working. Why the code above it's no working?
It is worth mentioning that the Byte Array is being constructed according to this other code here:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
The general idea is to record an audio with the smartphone and convert this audio file to a array of bytes. This String path is the path where the audio is being saved after recording. Then I use this path (that represents the audio file) and convert it to a byte array according to the code above.
More information you can find and help me here: How to solve this error: Android resource linking failed?
if you want to see value of bytes you can use as below:
Log.d("TAG", Arrays.toString(bytes));
What I'll try to do, based in what you guys said:
String decode = Arrays.toString(bytes);
Log.d("mytag", decode);
byte[] bytes = "ABCDEFG".getBytes();
System.out.println(new String(bytes)); // ABCDEFG
System.out.println(Arrays.toString(bytes)); // [65, 66, 67, 68, 69, 70, 71]

Android - Error when uploading a bitmap to server C#

When i make upload of a image in Android to the server (C #) it generates an error converting the image to byte Array, this happens with some images which is very strange because this error is not always generated, that is, depending the image is correctly converted or not.
The conversion code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 50, stream);
final byte[] img_byte = stream.toByteArray();
final String imageString = Base64.encodeToString(img_byte, Base64.DEFAULT);
When receiving in C# I make the following conversion in the string, generating a byte Array and then for the MemoryStream.
byte[] novaFoto = Convert.FromBase64String(NovaFoto.FotoString);
using (MemoryStream stream = new MemoryStream(novaFoto))
{
Image image = Image.FromStream(stream);
}
depending at the image the error appears in either Convert.FromBase64String or Image.FromStream.
Can anyone help me with this? If you have another method i like this.Thanks!!

How could I convert png binary data into bmp binary data in JAVA?

I got my binary data from database which is in PNG format. Now, I need to change the format to BMP and then convert it to a string by Base64.
My logic is PNG binary-->BMP binary-->BMP base64 String.
My Code is as below. The input "data" is the PNG binary, imageFormat="BMP".
public static String imageToBase64 (byte[] data, String imageFormat) throws IOException{
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
ImageIO.write(imag, imageFormat, baos);
String base64String=Base64.encodeBytes(baos.toByteArray());
return base64String;
}
However, the result always return empty. Can anyone help me to solve this problem?
Thanks
You need to use the Java API to write to a new BMP file. Based on your code this is how it does what you asked.
public static String imageToBase64(byte[] data, String imageFormat) throws IOException {
BufferedImage imag = ImageIO.read(new ByteArrayInputStream(data));
BufferedImage bmpImg = new BufferedImage(imag.getWidth(), imag.getHeight(), BufferedImage.TYPE_INT_RGB);
bmpImg.createGraphics().drawImage(imag, 0, 0, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bmpImg, imageFormat, baos);
String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());
return base64String;
}
Please note I used "bmp" (lowercase) instead of "BMP". Not sure if this matters. Enjoy.

Fetching the image data(stored as binary) from Hive with JDBC

I am fetching image data from a hive which is stored as binary data like
by using an InputStream object. The problem is when I am trying to encode the image, it's getting encoded but again when I am trying to decode the same encoded image it's throwing an error.
My program looks like this:
File file=new File("path");
java.io.InputStream in = rs1.getBinaryStream("entity_image");
OutputStream f = new FileOutputStream(file);
int c=0;
while((c=in.read())>-1)
{
//System.out.println(c);
f.write(c);
}
byte[] imageBytes = new byte[(int)file.length()];
in.read(imageBytes, 0, imageBytes.length);
in.close();
String imageStr = encodeImage(imageBytes);//method that returns the encoded base64 String.
byte[] imageByteArray = decodeImage(imgstring);//method returning byte []
f.write(imageByteArray);//writing the decoded image to the file
The new image file is saying that it contains error while opening?
Are there any other ways available for fetching the image data from the hive?
I checked with getbytes() method, but it says the method is not supported.

Converting bitmap to byte array, to string, then all the way back

I have tried several different methods found in the java documentation, as well as several solutions from other SO questions and have successfully gotten a Bitmap to convert to a byte[] and back again.
The problem is that I now need to convert this byte[] to a String, then back to a byte[], then back to a Bitmap again. To recap what I need:
Bitmap -> byte[] -> String -> byte[] -> Bitmap
I know this sounds strange but what I'm trying to accomplish must be done this way. Below is what I have tried, if anyone could point out what I'm doing wrong I'd greatly appreciate it!
Bitmap bitmap = mv.getDrawingCache();
// Convert bitmap to byte[]
ByteArrayOutputStream output = new ByteArrayOutputStream(bitmap.getByteCount());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
byte[] imageBytes = output.toByteArray();
// Convert byte[] to string
// I have also tried using Base64.encodeToString(imageBytes, 0);
String encodedString = new String(imageBytes);
// Convert string to byte[]
byte[] newImageBytes = encodedString.getBytes();
if (imageBytes == newImageBytes) {
Toast.makeText(SignatureActivity.this, "SUCCESS!!", Toast.LENGTH_SHORT).show();
} else { // Sadly, we always get to this point :(
Toast.makeText(SignatureActivity.this, "BOOO", Toast.LENGTH_SHORT).show();
}
// Convert byte[] back to bitmap
bitmap = BitmapFactory.decodeByteArray(newImageBytes, 0, newImageBytes.length);
Again, going Bitmap -> byte[] -> Bitmap was successful, but adding in the conversion to a String and back is causing the final Bitmap to write an image of 0kb.
The problem is not in the conversion, but how you verify the result. using == to compare two arrays only returns true if they are the same array reference. Since you create a new array with byte[] newImageBytes = encodedString.getBytes(); This will always be false.
See this question for reference.
On another note, if you are going to transfer or use the string in some way, it is probably better to use Base64.encodeToString(imageBytes, Base64.NO_WRAP); to get a string, and get it back with Base64.decode(encodedString, Base64.NO_WRAP).
You can also get the byte array without compressing it, with the copyPixelsToBuffer() method (see this question for an example).

Categories