Convert byte[] of RGB data to a image - java

I have a byte[] I captured from Kinect using OpenKinect and it's Java JNA wrapper. I'm wondering if there's any existing library I can use to convert the byte[] of RGB data into a image I can display/store?

Java's BufferedImage is a great candidate.
I would find out the color encoding scheme of your byte[] and transform it to an int[] acceptable for setting the RGB array of a BufferedImage with setRGB()javadoc. Then you can save the image to disk in a variety of formats, or render for display.
Writing/Saving an Imageoracle

You can convert the byte[] RGB data into an int[]where each int encodes an ARGB pixel (alpha, red, green, blue). Then use the following code to create a BufferedImage
int[] pixels = new int[width * height];
// do the conversion byte[] => int[]
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
img.setRGB(0, 0, width, height, pixels, 0, width);
You can then use ImageIO to save the image:
File outputFile = new File("image.png");
ImageIO.write(img, "png", outputFile);
Or draw the image for example in a JComponent's paint method:
public void paint(Graphics graphics){
Graphics2D g = (Graphics2D)graphics;
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
}
Consult the related JavaDoc for details. BufferedImage.TYPE_INT_ARGBis usually the fastest image encoding (at least it was a while ago on Mac OS X and Windows) even if you don't use any alpha at all.
Disclaimer: Code examples have not been tested.

Related

Image size increases after processing in Graphics2D

The following code results an image of higher size. My original image 200x200 was 6 KB. After the this I got an out put of 100KB.
When I resupply the output as input again, it is not changing the size
File imageFile = "path to image"
BufferedImage subImage= ImageIO.read(new FileInputStream(imageFile));
BufferedImage dest = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(subImage, 0, 0, 200, 200, null);
g2.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(dest, "png", out);
Image size varies depending on the format, compression and channels chosen.
PNG usually uses more size because it offers an alpha channel (which you used here) and does lossless compression, compared to JPEG.
Try chosing "JPEG" when writing the image, and check if the size and quality suits your needs better.

how to compress image with PNG extension [duplicate]

How can I save BufferedImage with TYPE_INT_ARGB to jpg?
Program generates me that image:
And it's OK, but when I save it in that way:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(byteStream);
try {
ImageIO.write(buffImg, "jpg", bos);
// argb
byteStream.flush();
byte[] newImage = byteStream.toByteArray();
OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\test.jpg"));
out.write(newImage);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The result is:
Understand that this is due to the alpha layer, but don't know how to fix it. Png format does not suit me, need jpg.
OK!
I've solved it.
Everything was pretty easy. Don't know is it a good decision and how fast it is. I have not found any other.
So.. everything we need is define new BufferedImage.
BufferedImage buffImg = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffImg.createGraphics();
// ... other code we need
BufferedImage img= new BufferedImage(buffImg.getWidth(), buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(buffImg, 0, 0, null);
g2d.dispose();
If there any ideas to improve this method, please, your welcome.
Images having 4 color channels should not be written to a jpeg file. We can convert between ARGB and RGB images without duplicating pixel values. This comes in handy for large images. An example:
int a = 10_000;
BufferedImage im = new BufferedImage(a, a, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = im.createGraphics();
g.setColor(Color.RED);
g.fillRect(a/10, a/10, a/5, a*8/10);
g.setColor(Color.GREEN);
g.fillRect(a*4/10, a/10, a/5, a*8/10);
g.setColor(Color.BLUE);
g.fillRect(a*7/10, a/10, a/5, a*8/10);
//preserve transparency in a png file
ImageIO.write(im, "png", new File("d:/rgba.png"));
//pitfall: in a jpeg file 4 channels will be interpreted as CMYK... this is no good
ImageIO.write(im, "jpg", new File("d:/nonsense.jpg"));
//we need a 3-channel BufferedImage to write an RGB-colored jpeg file
//we can make up a new image referencing part of the existing raster
WritableRaster ras = im.getRaster().createWritableChild(0, 0, a, a, 0, 0, new int[] {0, 1, 2}); //0=r, 1=g, 2=b, 3=alpha
ColorModel cm = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getColorModel(); //we need a proper ColorModel
BufferedImage imRGB = new BufferedImage(cm, ras, cm.isAlphaPremultiplied(), null);
//this image we can encode to jpeg format
ImageIO.write(imRGB, "jpg", new File("d:/rgb1.jpg"));

Java - Convert RAW to JPG/PNG

I have an image captured by a camera, in RAW BGRA format (byte array).
How can I save it to disk, as a JPG/PNG file?
I've tried with ImageIO.write from Java API, but I got error IllegalArgumentException (image = null)
CODE:
try
{
InputStream input = new ByteArrayInputStream(img);
BufferedImage bImageFromConvert = ImageIO.read(input);
String path = "D:/image.jpg";
ImageIO.write(bImageFromConvert, "jpg", new File(path));
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
Note that "img" is the RAW byte array, and that is NOT null.
The problem is that ImageIO.read does not support raw RGB (or BGRA in your case) pixels. It expects a file format, like BMP, PNG or JPEG, etc.
In your code above, this causes bImageFromConvert to become null, and this is the reason for the error you see.
If you have a byte array in BGRA format, try this:
// You need to know width/height of the image
int width = ...;
int height = ...;
int samplesPerPixel = 4;
int[] bandOffsets = {2, 1, 0, 3}; // BGRA order
byte[] bgraPixelData = new byte[width * height * samplesPerPixel];
DataBuffer buffer = new DataBufferByte(bgraPixelData, bgraPixelData.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, samplesPerPixel * width, samplesPerPixel, bandOffsets, null);
ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
System.out.println("image: " + image); // Should print: image: BufferedImage#<hash>: type = 0 ...
ImageIO.write(image, "PNG", new File(path));
Note that JPEG is not a good format for storing images with alpha channel. While it is possible, most software will not display it properly. So I suggest using PNG instead.
Alternatively, you could remove the alpha channel, and use JPEG.
With Matlab you can convert all types of images with 2 lines of code:
img=imread('example.CR2');
imwrite(img,'example.JPG');

How to convert Bufferedimage to indexed type and then extract the argb color palette

I need to convert a BufferedImage to a BufferedImage indexed type to extract the indices of the colors data and the 256 color palette.
i think that i am doing right the conversion of a BufferedImage to indexed mode and then extracting the color indices with the next code:
BufferedImage paletteBufferedImage=new BufferedImage(textureInfoSubFile.getWidth(), textureInfoSubFile.getHeight(),BufferedImage.TYPE_BYTE_INDEXED);
paletteBufferedImage.getGraphics().drawImage(originalBufferedImage, 0, 0, null);
// puts the image pixeldata into the ByteBuffer
byte[] pixels = ((DataBufferByte) paletteBufferedImage.getRaster().getDataBuffer()).getData();
My problem now is that i need to know the ARGB values of each color index( the palette) to put them into an array. i have been reading about ColorModel and ColorSpace but i donĀ“t find some methods to do what i need.
I think your code is good (except that you don't "put" any data into anything, you merely reference the data buffer's backing array, meaning changes in pixels will reflect to paletteBufferedImage and vice versa).
To get the ARGB values for the indices in pixels:
IndexColorModel indexedCM = (IndexColorModel) paletteBufferedImage.getColorModel(); // cast is safe for TYPE_BYTE_INDEXED
int[] palette = new int[indexedCM.getMapSize()]; // Allocate array
indexedCM.getRGBs(palette); // Copy palette to array (ARGB values)
For more information, see the IndexColorModel class documentation.
Finally i solve it with this code:
public static BufferedImage rgbaToIndexedBufferedImage(BufferedImage sourceBufferedImage) {
// With this constructor, we create an indexed buffered image with the same dimension and with a default 256 color model
BufferedImage indexedImage = new BufferedImage(sourceBufferedImage.getWidth(), sourceBufferedImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
ColorModel cm = indexedImage.getColorModel();
IndexColorModel icm = (IndexColorModel) cm;
int size = icm.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
WritableRaster raster = indexedImage.getRaster();
int pixel = raster.getSample(0, 0, 0);
IndexColorModel icm2 = new IndexColorModel(8, size, reds, greens, blues, pixel);
indexedImage = new BufferedImage(icm2, raster, sourceBufferedImage.isAlphaPremultiplied(), null);
indexedImage.getGraphics().drawImage(sourceBufferedImage, 0, 0, null);
return indexedImage;
}

BufferedImage Raster Data to BufferedImage

here's my code:
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
WritableRaster raster = newImage.getRaster();
raster.setDataElements(0, 0, image.getWidth(), image.getHeight(), pixels);
newImage.setData(raster);
ImageIO.write(newImage, "jpg", new File("newimage.jpg"));
This code looks right to me and should do what I want. It gets the image's pixel data, then uses it to create a new image which should look exactly the same as the original image. However, the image that is saved has different colors than the original. Why?
Eventually, I'll need to manipulate the pixel bytes but for now, I don't know why it's giving me a different image.
This post may be of help java buffered image created with red mask
It seems to be a common problem with ImageIO so its best to use Toolkit instead.

Categories

Resources