Drawing BufferedImage using ImageIO.write causing image to be resized - java

I have this code:
public void draw(File image, int number, File destination) {
BufferedImage img = null;
try {
img = ImageIO.read(image);
//create graphic object
Graphics2D graphicImg = img.createGraphics();
//select the font
Font font = new Font("TimesRoman", Font.BOLD, 96);
graphicImg.setFont(font);
//draw the text
graphicImg.drawString(String.valueOf(number), 100, 100);
//save on disk
ImageIO.write(img, "jpg", destination);
} catch (Exception e) {
System.out.println("Error while trying to write on image!");
}
}
I pass a File (which will be an image) as first parameter, an int and a File(which will represent the destination) of the file.
The method should draw a number on this file.
The problem is that the image size of the new image will be lower than original. For example, if I give a image with 3Mb as first parameter, the saved image will have around 1.5Mb. Why the size are so different and how I can fix it?
Thank you

Related

Get a specific version of the icon of a file in Java

I was looking at this question and I was looking at the first answer.
So I tried to use this code:
public static Image getIcon(String fileName) throws Exception {
File file = new File(fileName);
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(file);
ImageIcon imageIcon = (ImageIcon) icon;
Image image = imageIcon.getImage();
return image;
}
Which does return an Image (or throws an Error) but the Image has terribly low resolution.
I am assuming that this is because the 16x16 Image is returned.
Is there any way to state which Image I want to be returned?
Java offers you two possibilities to retrieve file icons.
You already know the first one:
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(new File(FILENAME));
that gives you a 16x16 pixel result.
The other one using ShellFolder
Icon icon = new ImageIcon(ShellFolder.getShellFolder(new File(FILENAME)).getIcon(true));
will retrieve you the larger one (32x32) depending on the boolean flag getLargeIcon in the getIcon method.
I'm sorry for you but more is (at the moment) not possible with the java default libraries. Interest exists as you can read in this JDK bugreport.
But nothing has been done so far.
If you really want to have larger versions you will need to retrieve them with the OS depending native calls or store them manually as local application ressources.
Note: If you have problems accessing ShellFolder you should read this question.
I used this method:
protected ImageIcon getImageIcon() {
File f = new File((iconPath!=null)?iconPath:"");
if (!f.isFile() || !f.canRead()) {
iconPath = Constants.getDefaultPreviewIconPath();
}
ImageIcon icon = new ImageIcon(iconPath, titolo);
return new ImageIcon(Utils.getScaledImage(
icon.getImage(),
Constants.getICON_WIDTH(),
Constants.getICON_HEIGTH()));
}
where getScaledImage is:
public static Image getScaledImage(Image srcImg, int w, int h) {
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}

Resize a picture to fit a JLabel

I'm trying to make a picture fit a JLabel. I wish to reduce the picture dimensions to something more appropriate for my Swing JPanel.
I tried with setPreferredSize but it doesn't work.
I'm wondering if there is a simple way to do it? Should I scale the image for this purpose?
Outline
Here are the steps to follow.
Read the picture as a BufferedImage.
Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
Create an ImageIcon from the resized BufferedImage.
You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.
Read the picture as a BufferedImage
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Resize the BufferedImage
Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
Image.SCALE_SMOOTH);
Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.
Create an ImageIcon
ImageIcon imageIcon = new ImageIcon(dimg);
You can try it:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Or in one line:
label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));
The execution time is much more faster than File and ImageIO.
I recommend you to compare the two solutions in a loop.
public static void main(String s[])
{
BufferedImage image = null;
try
{
image = ImageIO.read(new File("your image path"));
} catch (Exception e)
{
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
jLabel1.setIcon(imageIcon);
}
private Image fitimage(Image img , int w , int h)
{
BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedimage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0,w,h,null);
g2.dispose();
return resizedimage;
}
The best and easy way for image resize using Java Swing is:
jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));
For better display, identify the actual height & width of image and resize based on width/height percentage
i have done the following and it worked perfectly
try {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
Image bi = ImageIO.read(f);
image1.setText("");
image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));
} catch (Exception e) {
}
Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.
BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics();
Image img=ImageIO.read(new File("path of your image"));
g.drawImage(img, 0, 0, label.width(), label.height(), null);
g.dispose();
return bi;
public void selectImageAndResize(){
int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
if (returnVal == jFileChooser.APPROVE_OPTION) { //select image
File file = jFileChooser.getSelectedFile(); //get the image
BufferedImage bi;
try {
//
//transforms selected file to buffer
//
bi=ImageIO.read(file);
ImageIcon iconimage = new ImageIcon(bi);
//
//get image dimensions
//
BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
iconimage.paintIcon(null, g, 0,0);
g.dispose();
//
//resize image according to jlabel
//
BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight());
ImageIcon resizedicon=new ImageIcon(resizedimage);
jLabel2.setIcon(resizedicon);
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
Assign your image to a string.
Eg image
Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));

Find format of clipboard image in Java

I'm getting images from clipboard using this:
if(Toolkit.getDefaultToolkit().getSystemClipboard().isDataFlavorAvailable(DataFlavor.imageFlavor)){
ImageIcon IMG = new ImageIcon((BufferedImage) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor));
}
Now I want to save this image in disk using ImageIO.write;
How can I find image format (JPG,PNG,GIF,...) to use in ImageIO.write as formatName ?
Thanks
The mime type of the content of the clipboard when checked via
.isDataFlavorAvailable(DataFlavor.imageFlavor)
is image/x-java-image (but OS vendors do not need to follow MIME types for clipboards).
I found two ways to supposedly get an image from a clipboard and write it to a file:
Using a helper method found in this blog post: The nightmares of getting images from the Mac OS X clipboard using Java.
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard()
ImageIcon IMG = new ImageIcon((BufferedImage)
clip.getData(DataFlavor.imageFlavor));
BufferedImage bImage = getBufferedImage(IMG.getImage());
ImageIO.write(bImage, "png", new File("/tmp/test.png"));
The getBufferedImage method looks like this:
public static BufferedImage getBufferedImage(Image img) {
if (img == null) {
return null;
}
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
Via Transferable. Note that this runs on OS X but produces an empty image of the correct size:
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard()
Transferable content =
clip.getContents(null);
BufferedImage img = (BufferedImage) content.getTransferData(
DataFlavor.imageFlavor);
ImageIO.write(img, "png", new File("/tmp/test.png"));

Java PNG to JPG Bug

I am trying to convert a PNG image to a JPEG image following this tutorial. But I encounter a problem. The resulting image has a pink layer.
Does anyone have a solution for this problem? Or what code should I use in order to convert the image into the desired format?
Thanks in advance!
Create a BufferedImage of desired size, e.g.:
BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB)
fill it with a proper background color:
img.getGraphics().fillRect(....)
Call drawImage on the image's graphics atop of that background:
img.getGraphics().drawImage(image, 0, 0, null);
then write down your image as JPG as usual.
Which color mode are you using? While you create buffered image object, try adding the type like this option.
File newFile = new File(path + fileName + "." + Strings.FILE_TYPE);
Image image = null;
try {
image = ImageIO.read(url); // I was using an image from web
} catch (IOException e1) {
e1.printStackTrace();
}
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
try {
BufferedImage img = toBufferedImage(image);
ImageIO.write(img, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage toBufferedImage(Image src) {
int w = src.getWidth(null);
int h = src.getHeight(null);
int type = BufferedImage.TYPE_INT_RGB; // other options
BufferedImage dest = new BufferedImage(w, h, type);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(src, 0, 0, null);
g2.dispose();
return dest;
}

How to select a portion of an image and save just that portion to a file

I am taking a screenshot of the current screen then saving the image. I want to open that image up and be able to select a box of a certain element or whatever it is i want the pic to be of and to be able to in turn save that smaller selected image to
a file. Please help.
RemoteControlConfiguration config = new RemoteControlConfiguration();
config.setPort(4447);
SeleniumServer server = new SeleniumServer(config);
try{
// TODO Auto-generated method stub
server.start();
DefaultSelenium selenium = new DefaultSelenium("localhost", 4447, "*firefox", "http://www.google.com/");
selenium.start();
selenium.open("http://www.google.com/");
selenium.waitForPageToLoad("10000");
selenium.windowMaximize();
BufferedImage image1 = Screenshot("screen1.jpg");
//selenium.type("q", "Hello world");
Thread.sleep(2000);
BufferedImage image2 = Screenshot("screen2.jpg");
public static BufferedImage Screenshot(String fileName) throws Exception
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
File file = new File(fileName);
ImageIO.write(image, "jpg", file);
return image;
}
Assuming you know the coordinates of your new bounds, create a new BufferedImage with the new size, create a graphics object for your new image, and paint the big image on this graphics object, specifying negative values for the x,y. The source image is bigger than the destination, so only the bits that fit within the destination will be written. Then you save out the smaller one using ImageIO.write()
EDIT
Thanks to Andrew Thompson for the suggestion to use subImage
BufferedImage image1 = Screenshot("screen1.jpg");
BufferedImage subImage = image1.getSubImage(x, y, width, height);

Categories