I need to add a CMYK Image (java.awt.BufferedImage) to a Pdf-Document with iText.
I'm trying to do it with:
com.lowagie.text.Image img = Image.getInstance(BufferedImage, bgColor);
This produces an RGB image in the resulting PDF. (and I suppose it's a bug, because it just ignores ColorModel). However I could use:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);
And it produces a correct CMYK-Image in PDF. But for the second case I need to convert java.awt.BufferedImage in ByteArray. I cannot do it with ImageIO.write(ByteArrayOutputStream). I also cannot do it with com.sun.image.codec.jpeg.JPEGImageEncoder because I must use OpenJDK.
Any ideas how can I achieve the correct behavior to write a CMYK image in PDF using iText?
So basically what you're asking is how to convert a BufferedImage to a byte[] to print to PDF?
BufferedImage img; // your image to be printed
String formatName; // name of the image format (see ImageIO docs)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, formatName, baos);
byte[] rawData = baos.toByteArray();
You should be able to use that for the CMYK-image as you had in your original post:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);
Related
I have a ReadableByteChannel which contains an image (either obtained from an URL or a file). I write the Channel finally into a File with a code like
final FileOutputStream fileOutputStream = new FileOutputStream(outImageName);
fileOutputStream.getChannel().transferFrom(imageByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
Since it is unclear if the image is a png or a jpeg or ... I want to make sure and save it as png. I know I can use the ImageIO.write(buffImg, outImageName, "png");
But somehow this requires that the buffImg is a RenderedImage which raises the question how to obtain it?
Is there a simpler solution than reading the file from the file system with ImageIO and than write it as png? Can I convert it directly within the memory?
Plus an additional question: Is there a way to tell ImageIO to get rid of the AlphaChannel (=transparent)?
If you can, I suggest getting the InputStream or the underlying File or URL objects instead of a ReadableByteChannel, as ImageIO.read(..) supports all those types as input directly.
If not possible, you can use Channels.newInputStream(..) to get an InputStream from the byte channel, to pass on to ImageIO.read(...). There's no need to write to a file first.
Code:
ReadableByteChannel channel = ...; // You already have this
BufferedImage image = ImageIO.read(Channels.newInputStream(channel))
To get rid of any unwanted transparency, you could do:
BufferedImage opaque = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = opaque.createGraphics();
try {
g.setColor(Color.WHITE); // Or any other bg color you like
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(image, 0, 0, null);
}
finally {
g.dispose();
}
You can now write the image in PNG format, either to a file or stream:
if (!ImageIO.write(opaque, "PNG", new File(outputFile)) {
// TODO: Handle odd case where the image could not be written
}
I have a Spring MVC Web Service that returns an image as a byte array. The output is in json format. The format is png
Here's the code snippet for the image.
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
imagem = ((DataBufferByte) img.getRaster().getDataBuffer
()).getData();
When I run the server, this is the output:
[{"id":0,"caminhoMDPI":null,"caminhoHDPI":"C:/Users/Marcos/Pictures/postos/drawable-
mdpi/esso_logo.png","caminhoXHDPI":null,"caminhoXXHDPI":null,"imagem":"AAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAA....]
Eventually, other symbols appear on the "imagem" field. I suppose this is right, but I'm not
sure.
On my Android app, I have a routine to download the image and store it as a blob in the database. I receive the json format and transform it into a class with jackson. I've logged the "imagem" field and it looks the same.
My problem is that I can't transform it into an image. Here's the code snippet:
byte[] img_bandeira = cursor.getBlob(cursor.getColumnIndex("img_bandeira"));
Bitmap bmpBandeira = BitmapFactory.decodeByteArray(img_bandeira, 0, img_bandeira.length);
ImageView ivBandeira = (ImageView) view.findViewById(R.id.ivBandeira);
ivBandeira.setImageBitmap(bmpBandeira);
All I get is a message: skImageDecoder::Factory returned null.
I've looked at other similar posts, tried to change some lines, but nothing happened. I don't know what's going on here. Thanks in advance.
I solved it. In the server, the image should be sent like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage img = ImageIO.read(new File(caminho.replace("/", "//")));
ImageIO.write(img, "png", baos);
baos.flush();
String base64String = Base64.encode(baos.toByteArray());
baos.close();
In my app, it should be read like this:
public static Bitmap getImage(byte[] imageArray) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageArray);
Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
return bitmap;
}
Thank you, everybody ;)
I am trying to create a helper function using OpenCV Java API that would process an input image and return the output byte array. The input image is a jpg file saved in the computer. The input and output image are displayed in the Java UI using Swing.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Load image from file
Mat rgba = Highgui.imread(filePath);
Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);
// Convert back to byte[] and return
byte[] return_buff = new byte[(int) (rgba.total() * rgba.channels())];
rgba.get(0, 0, return_buff);
return return_buff;
When the return_buff is returned and converted to BufferedImage I get NULL back. When I comment out the Imgproc.cvtColor function, the return_buff is properly converted to a BufferedImage that I can display. It seems like the Imgproc.cvtColor is returning a Mat object that I couldn't display in Java.
Here's my code to convert from byte[] to BufferedImage:
InputStream in = new ByteArrayInputStream(inputByteArray);
BufferedImage outputImage = ImageIO.read(in);
In above code, outputImage is NULL
Does anybody have any suggestions or ideas?
ImageIO.read(...) (and the javax.imageio package in general) is for reading/writing images from/to file formats. What you have is an array containing "raw" pixels. It's impossible for ImageIO to determine file format from this byte array. Because of this, it will return null.
Instead, you should create a BufferedImage from the bytes directly. I don't know OpenCV that well, but I'm assuming that the result of Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0) will be an image in grayscale (8 bits/sample, 1 sample/pixel). This is the same format as BufferedImage.TYPE_BYTE_GRAY. If this assumption is correct, you should be able to do:
// Read image to Mat as before
Mat rgba = ...;
Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0);
// Create an empty image in matching format
BufferedImage gray = new BufferedImage(rgba.width(), rgba.height(), BufferedImage.TYPE_BYTE_GRAY);
// Get the BufferedImage's backing array and copy the pixels directly into it
byte[] data = ((DataBufferByte) gray.getRaster().getDataBuffer()).getData();
rgba.get(0, 0, data);
Doing it this way, saves you one large byte array allocation and one byte array copy as a bonus. :-)
I used this kind of code to convert Mat object to Buffered Image.
static BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {
MatOfByte mob=new MatOfByte();
Imgcodecs.imencode(".jpg", matrix, mob);
byte ba[]=mob.toArray();
BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
return bi;
}
Hi I have a byte array that I am converting to jpg image but that is giving exception as below please explain me wht is the problem with this.
ByteArrayInputStream bis = new ByteArrayInputStream(someByteArray);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
//ImageIO is a class containing static methods for locating ImageReaders
//and ImageWriters, and performing simple encoding and decoding.
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
BufferedImage image = reader.read(0, param);
//got an image file
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File("D:\\newrose2.jpg");
ImageIO.write(bufferedImage, "jpg", imageFile);
Exception:
javax.imageio.IIOException: Invalid JPEG file structure: SOS before SOF
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:550)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:295)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:427)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:543)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:986)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:966)
at Trnsport.writejpegfile(Trnsport.java:398)
at Trnsport.getData(Trnsport.java:107)
at Trnsport.run(Trnsport.java:63)
at java.lang.Thread.run(Thread.java:722)
Edit:
FileOutputStream fos = new FileOutputStream("image" + new Date().getTime() + ".jpg");
fos.write(someByteArray);
fos.close();
If your byte array already contains valid JPEG data, you do not need to invoke the JPEG reader or writer -- you can write the bytes to the file using ordinary file I/O.
If the byte array actually contains some format of raw pixel data, you will need to load it into a BufferedImage directly (such as via setRGB) and encode that as a JPEG.
The fact that you're getting an exception trying to decode it implies it is not JPEG data, but raw pixel data. Or, perhaps it is a different type of image altogether, or it has an image at some offset into the array instead of at the start the array, or it is not an image at all.
I tried to create image from BLOB. I try following code but it is not working at step:
ImageIO.write(image, "JPG", iio);)
image is null. Please give me any suggestion.
byte[] imgData = null;
if (rs.next ())
{
Blob img = rs.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
File f1 = new File(fillFilePath); //fillFilePath = path where image want to store
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgData));
ImageOutputStream iio = ImageIO.createImageOutputStream(f1);
ImageIO.write(image, "JPG", iio);
}
How to create image from BLOB using ImageIO?
From the JavaDoc on ImageIO.read(InputStream):
If no registered ImageReader claims to be able to read the resulting stream, null is returned.
It seems your blob doesn't represent an image format that ImageIO is able to understand. What format does the image stored in the blob have?
Below code works for me. I am able to retrieve BLOB(oracle)/binary(hive) from hive:
InputStream is=rs.getBinaryStream(1);
toImage(is,"C:\\hive_image.png");
public void toImage(InputStream is,String imagePath) throws IOException
{
BufferedImage bufferedImage=ImageIO.read(is);
ImageIO.write(bufferedImage, "png", new File(imagePath));
}