I have a simple java program which takes a jpeg image as input, draws a line and a rectangle on that then saves it. I want the lines and rectangle to be red but in result images they are always black,white or grey; it depends on what color i set for the lines.
This is the simple code
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
public class Lines {
public static void main(String[] args) {
BufferedImage image = null;
File filePath = new File("C:\\Users\\agelormini\\Desktop\\big.jpg");
com.sun.image.codec.jpeg.JPEGImageDecoder jpegDecoder = null;
try {
jpegDecoder = JPEGCodec.createJPEGDecoder (new FileInputStream(filePath));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
try {
image = jpegDecoder.decodeAsBufferedImage();
} catch (ImageFormatException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.RED);
g2d.drawLine(131, 220, 216, 222);
g2d.drawRect(164, 157, 268 - 164, 287 - 157);
g2d.drawLine(165, 229, 174, 135);
File dest = new File("C:\\Users\\agelormini\\Desktop\\big_mod.jpg");
try {
ImageIO.write(image, "jpg", dest);
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this case lines will be black, with yellow will be white...I don't understand why this happens. Any suggestion?
thanks
I managed to resolve the problem using this little convert function
public static BufferedImage convert(BufferedImage src, int bufImgType) {
BufferedImage img= new BufferedImage(src.getWidth(), src.getHeight(), bufImgType);
Graphics2D g2d= img.createGraphics();
g2d.drawImage(src, 0, 0, null);
g2d.dispose();
return img;
}
if i add this line to the previous code just before the Graphics2D creation it works:
image = convert(image, BufferedImage.TYPE_INT_BGR);
I had to use TYPE_INT_BGR since ARGB resulted in wrong colors of the previous image. I am in win environment so its not a problem
thank you for the help!