convert raw image bytes to multipage tiff using java and vice versa - java

I have a requirement where i have set of base64 strings each string is one tiff file, i need to combine all these base64 strings and provide this full tiff data as base64 string, so end user can create a tiff file from the combined base64 strings.
I tried all the ways shared below but each time in my output tiff only one page is coming but i am passing 2 base64 strings.
Any inputs greatly appreciated.
Iam using this code
ArrayList al = new ArrayList();
//this is repetative so i am adding all the base64 strings to arraylist
byte[] imgBytes = Base64.decodeBase64(imageObject.get("image").toString());
al.add(imgBytes);
//writing all base64 strings to a new tiff file //here it is showing only the first page but in the top i am adding two pages.
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(toByteArray(al)));
ImageIO.write(imag, "tif", new File(processedFilesFolder,"combined.tif"));
public static byte[] toByteArray(List<byte[]> bytesList)
{
int size = 0;
for (byte[] bytes : bytesList)
{
size += bytes.length;
}
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
for (byte[] bytes : bytesList)
{
byteBuffer.put(bytes);
}
return byteBuffer.array();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( data ); // this line is repetative
byte c[] = outputStream.toByteArray( );
try (OutputStream stream = new FileOutputStream("C:\\Users\\XYZ\\Desktop\\EID_Image_Desktop‌​Scan_mod.tiff")) { stream.write(c); } catch(Exception e){}
Regards,
Meerasaaheb Mohmmad

Related

Trying to use BufferedInputStream and Base64 to Encode a large file in Java

I am new to the Java I/O so please help.
I am trying to process a large file(e.g. a pdf file of 50mb) using the apache commons library.
At first I try:
byte[] bytes = FileUtils.readFileToByteArray(file);
String encodeBase64String = Base64.encodeBase64String(bytes);
byte[] decoded = Base64.decodeBase64(encodeBase64String);
But knowing that the
FileUtils.readFileToByteArray in org.apache.commons.io will load the whole file into memory, I try to use BufferedInputStream to read the file piece by piece:
BufferedInputStream bis = new BufferedInputStream(inputStream);
StringBuilder pdfStringBuilder = new StringBuilder();
int byteArraySize = 10;
byte[] tempByteArray = new byte[byteArraySize];
while (bis.available() > 0) {
if (bis.available() < byteArraySize) { // reaching the end of file
tempByteArray = new byte[bis.available()];
}
int len = Math.min(bis.available(), byteArraySize);
read = bis.read(tempByteArray, 0, len);
if (read != -1) {
pdfStringBuilder.append(Base64.encodeBase64String(tempByteArray));
} else {
System.err.println("End of file reached.");
}
}
byte[] bytes = Base64.decodeBase64(pdfStringBuilder.toString());
However, the 2 decoded bytes array don't look quite the same... ... In fact, the only give 10 bytes, which is my temp array size... ...
Can anyone please help:
what am I doing it wrong to read the file piece by piece?
why is the decoded byte array only returns 10 bytes in the 2nd solution?
Thanks in advance:)
After some digging, it turns out that the byte array's size has to be multiple of 3 in order to avoid padding. After using a temp array size with multiple of 3, the program is able to go through.
I simply change
int byteArraySize = 10;
to be
int byteArraySize = 1024 * 3;

Issues in converting base64 decoded byte array to String in java

Issues in converting base64 decoded byte array to String in java :
public static String decode(String strcontent) throws Exception
{
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgBytes = decoder.decodeBuffer(strcontent);
return new String(imgBytes);
}
With the above code; was trying to create a string out of the Base 64 decoded byte array (imgBytes ) & input strcontent is base 64 encoded string. For text files it working fine , but for PDF and image files the string conversion is having issues. Have tried different encoding as UTF-8 , UTF 16 etc. But no use. The returned string is different than the original one.
When tried to write the byte array to a file like :
OutputStream out = new FileOutputStream(##path);
out.write(imgBytes);
out.close();
File is getting created properly without any issues.
I tried the below code:
byte[] imgBytes= ( new String(imgBytes1)).getBytes(); //Converting to String and back to bytes
OutputStream out = new FileOutputStream(##Filename);
out.write(imgBytes); out.close();
This time the image file is corrupted.
Please suggest.

Show image from Data URI scheme on Java panel

I am having trouble interpreting this question.
I receive a img in JSON formated in Base64, for web developers its only do:
"".
How I can make it in Java?
You can use apache commons-codec for converting byte array. to base64 and from base64 to byte array.
Actually, you can use guava. This artifact has base64 libraries and json.
Just add com.google.guava in your maven's project.
For creating image, you can use:
InputStream in = new ByteArrayInputStream(yourbytearray);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new File("c:/yourimage.jpg"));
//JSON funtion
String cmd_getPhoto = so.cmd_getPhoto();
//for remove ":"data:image\/png;base64,"
String imageDataBytes = cmd_getPhoto.substring(cmd_getPhoto.indexOf(",") + 1);
//for decode
Base64 b = new Base64();
byte[] decode = b.decode(imageDataBytes.getBytes());
//create the stream
InputStream stream = new ByteArrayInputStream(decode);
try {
//set the stream for a bufferedImage and do what your will with it
BufferedImage bitmap = ImageIO.read(stream);
jLabel6.setIcon(new ImageIcon(bitmap));
} catch (IOException ex) { }

Java encode raw bytes into image simple image fomat/ file

I am very new to image encoding and would rather not learn a whole lot about it. Basically I'm taking greyscale byte array where each byte equals one pixel. I'm getting this data from mnist where I get 28x28 byte images. Anyway, bellow is my code, so you understand what I'm trying to accomplish.
private def getImages = {
val filePath = getClass.getResource("/mnist/train-images.idx3-ubyte").getPath
val fis = new FileInputStream(filePath)
var bytes = new Array[Byte](4)
fis.read(bytes)
println((ByteBuffer.wrap(bytes).getInt()))
fis.read(bytes)
println((ByteBuffer.wrap(bytes).getInt()))
fis.read(bytes)
var rows = ByteBuffer.wrap(bytes).getInt()
println("Number of rows: " + rows)
fis.read(bytes)
var cols = ByteBuffer.wrap(bytes).getInt()
println("Number of cols: " + cols)
var imageBytes = new Array[Byte](rows * cols)
fis.read(imageBytes)
imageBytes.foreach(println(_))
// I created a byte array input stream to feed into ImageIO
// which should create my image
val b = new ByteArrayInputStream(imageBytes)
// This is where your helpful answer would be placed
// What is the code to encode this into jpeg, gif, or whatever?
// This returns null because I have not encoded the bytes
// in the proper format
val img = ImageIO.read(b)
// Errors out because img is null
ImageIO.write(img, "gif", new File("/home/dev/woot.gif"))
}
The format is just consecutive pixel bytes laid next to each other. My question is what Java library or function is available to convert these raw bytes into jpeg, gif, or whatever format I need?
Before you write it out with ImageIO, create a BufferedImage first. It can be as simple as using the setRGB methods, and has the added benefit of allowing you to observe the image before writing it out.

Display image with base64 String in html?

here is my java code that construct the base64 String from image. Then place the base64 String html, to view
the constructed image, but image is not constructed somehow
public void getBase64String() throws FileNotFoundException {
FileInputStream itStrm = new FileInputStream(
"E:\\image\\56255254-flower.jpg");//image is lying at http://danny.oz.au/travel/mongolia/p/56255254-flower.jpg
String str = itStrm.toString();
byte[] b3 = str.getBytes();
String base64String = new sun.misc.BASE64Encoder().encode(b3);
//output of base64String is amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA==
}
Now in html page i placed the output of base64String in img tag to view the image.But image does not shows up
(instead it display the cross image icon). I am not getting image is not displayed from base64 String below?
<HTML>
<BODY>
<img src="data:image/jpeg;base64,amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA=="/>
</BODY>
</HTML>
EDIT:- Thanks Folks, i used byte[] bytes = IOUtils.toByteArray(is);. It worked for me!!
This: String str = itStrm.toString() is not the image but the toString() representation of the FileInputStream instance.
You'll have to read the bytes from the stream and store them in a byte array. And, for performance reasons, buffer the stream:
BufferedInputStream itStrm = new BufferedInputStream(FileInputStream(
"E:\\image\\56255254-flower.jpg"));
Further reading (Spoiler: solution inside)
Convert InputStream to byte array in Java
You would need to use the read() method of the FileInputStream instance instead of the toString() to get the content of the image. Then you are able to encode it and should work as you expected.
Something like:
int c;
StringBuffer result = new StringBuffer("");
while((c = fileInputStream.read()) != -1)
{
result .append((char)c);
}

Categories

Resources