How to resize tiff image in java? - java

I want to resize a .tiff file. I have used JAI toolkit to resize different types of images. Here is what I have tried to implement:
int imageWidth = 330;
int imageHeight = 490;
BufferedImage tempImage = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = tempImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(tempImage, 0, 0, imageWidth, imageHeight, null);
graphics2D.dispose();
File outfile = new File("D:/Work/YoursGallery/output.tif");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile));
FileSeekableStream ss = new FileSeekableStream("D:/Work/YoursGallery/sample1.tif");
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", ss, null);
TIFFEncodeParam param = new TIFFEncodeParam();
param.setTileSize(tempImage.getWidth(), tempImage.getHeight());
TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param);
encoder.encode(dec.decodeAsRenderedImage());
out.close();
The image created is having same size as original image has. Can anyone please tell what is the issue?
Here is the sample tiff image which I am using to test it.
http://docs.google.com/fileview?id=0BxCDhEXNFvbeMTYyMGZmNDYtODhhNy00YWI3LTkxNDgtZTNhM2FhMjg5Y2Q3&hl=en&authkey=CPCEypgM
Thanks in advance.

That's because you are writing out tempImage which is still the original image.
graphics2D.drawImage(image, 0, 0, imageWidth, imageHeight, null);
change that to:
graphics2D.drawImage(tempImage, 0, 0, imageWidth, imageHeight, null);
or change your other code to write out image instead of tempImage
--Edit--
OK Attempt 2. Maybe having the source and destination the same is daft.
BufferedImage bsrc = ImageIO.read(new File(src));
BufferedImage bdest =
new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at =
AffineTransform.getScaleInstance((double)width/bsrc.getWidth(),
(double)height/bsrc.getHeight());
g.drawRenderedImage(bsrc,at);
Try that :)

1) You are writing tempImage inside itself:
graphics2D.drawImage(tempImage, 0, 0, imageWidth, imageHeight, null);
Should be:
graphics2D.drawImage(originalImage, 0, 0, imageWidth, imageHeight, null);
2) You are writing the image that you just read (why are You reading it btw?):
encoder.encode(dec.decodeAsRenderedImage());
Should be:
encoder.encode(tempImage);

Related

Convert color image into black and white using java created from scratch

I want to convert my picture from colored to Black and white which seems to be created from scratch.
Here is the code which i tried as described on the different post:
BufferedImage bi = ImageIO.read(new File("/Users/***/Documents/Photograph.jpg"));
ColorConvertOp op =
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
ImageIO.write(bi, "PNG", new File("/Users/bng/Documents/rendered2.png"));
op.filter(bi, bi);
But still my image is not converted to the Black and white. Additionally, this code is increasing the rendered2.png image size to 10 folds.
Also, it would be great if i could find some Java 8 way of doing this.
Any suggestions?
Here is the code which worked for me:
BufferedImage input = ImageIO.read(new File("/Users/bng/Documents/Photograph.jpg"));
// Create a black-and-white image of the same size.
BufferedImage im = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
// Get the graphics context for the black-and-white image.
Graphics2D g2d = im.createGraphics();
// Render the input image on it.
g2d.drawImage(input, 0, 0, null);
// Store the resulting image using the PNG format.
ImageIO.write(im, "PNG", new File("/Users/bng/Documents/rendered.png"));
It was BufferedImage.TYPE_BYTE_BINARY which provided me the exact solution.
Lokking for the Java 8 Version for above code.
You have to find RGB of the existing colors of the image you want to change it.
Fyi, you want to change it as white RGB value is (255,255,255) and for black RGB value is (0,0,0)
Following method easily do the color change if you apply correct way of your requirement
private BufferedImage changeColor(BufferedImage image, int srcColor, int replaceColor)
{
BufferedImage destImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = destImage.createGraphics();
g.drawImage(image, null, 0, 0);
g.dispose();
for (int width = 0; width < image.getWidth(); width++)
{
for (int height = 0; height < image.getHeight(); height++)
{
if (destImage.getRGB(width, height) == srcColor)
{
destImage.setRGB(width, height, replaceColor);
}
}
}
return destImage;
}
you have to use the ColorConvertOp in a proper way:
create Source image
apply filter
save dest
example:
BufferedImage src = ImageIO.read(new File("/Users/***/Documents/Photograph.jpg"));
ColorConvertOp op =
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage dest = op.filter(src, null);
ImageIO.write(dest, "PNG", new File("/Users/bng/Documents/rendered2.png"));
src:
dest:

How to convert an image to greyscale?

I want to simply convert an image to greyscale. But all I get is a completely black image. Why?
BufferedImage original = ImageIO.read(url);
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
It has the correct width and height like the source image, but is completely black...
You are writing empty image to itself.
Change
g.drawImage(image, 0, 0, null);
to
g.drawImage(original, 0, 0, null);

Itext barcode under text

When I create a image using code128.createImageWithBarcode() the text under barcode appears in the doc, but when I try to create using createAwtImage and later saving it to disc, the text under the barcode dissapear. Any idea about how to handle it?
Barcode128 code128 = new Barcode128();
code128.setCode(code.trim());
code128.setCodeType(Barcode128.CODE128);
Image code128Image = code128.createImageWithBarcode(cb, null, null);
java.awt.Image imgShipBarCode = code128.createAwtImage(Color.white, Color.black);
int w = imgShipBarCode.getWidth(null);
int h = imgShipBarCode.getHeight(null);
int type = BufferedImage.TYPE_INT_RGB; // other options
BufferedImage dest = new BufferedImage(w, h, type);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(imgShipBarCode, 0, 0, null);
g2.dispose();
File outputfile = new File("c:\\image.jpg");
ImageIO.write(dest, "jpg", outputfile);
code128Image.setAbsolutePosition(10,700);
code128Image.scalePercent(125);
doc.add(code128Image);
Thanks
Set Font to null
code128.Font = null;

How to obtain a resized BufferedImage

Say I have 2 TIF images and I read one of them into a BufferedImage instance:
ImageReader reader = ImageIO.getImageReadersByFormatName("tif").next();
reader.setInput(inputStream, false); // inputStream is the first image.
BufferedImage bufferedImage = reader.read(0);
Now I want to create a new BufferedImage without reading the other image. It should be the same as the previous one, but only different in size. imageType seems to be 0 for TIF images, but the following doesn't work.
BufferedImage largeBufferedImage = new BufferedImage(newWidth, newHeight, 0);
Is there any way to clone the existing BufferedImage and only change its size?
BTW I want to be able to do it for any image format. I don't want to deal with details like imageType if possible.
BufferedImage deepCopy(BufferedImage bi)/*method to clone BufferedImage*/ {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
BufferedImage newImg = deepCopy(oldImg);//clone it
Graphics2D g = newImg.createGraphics();
g.drawImage(newImg, 0, 0, width, height, null);//newImg will be resized
When you draw in your paint method, you can add more parameters to stretch and scale image, see g.drawImage at this link.
After some trial and error, I found a working solution for my problem.
private BufferedImage copyAndResize(BufferedImage source, int width, int height)
{
ColorModel cm = source.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = source.copyData(null);
SampleModel sm = raster.getSampleModel().createCompatibleSampleModel(width, height);
WritableRaster newRaster = WritableRaster.createWritableRaster(sm, null);
BufferedImage newBi = new BufferedImage(cm, newRaster, isAlphaPremultiplied, null);
return newBi;
}

Java ARGB to JPG

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"));

Categories