I am working to create a GUI that will save an Image drawn on a JLabel by a user. Here is the code that I have for my saveImage method. I can get the box to pop up so that I can select where to save the file, but no file is actually saved.
public void saveImage()
{
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D image2 = image.createGraphics();
image2.setBackground(Color.WHITE);
image2.clearRect(0, 0, this.getWidth(), this.getHeight());
this.paintAll(image2);
try
{
File output = new File("rectangle.png");
ImageIO.write(image, "Rectangles", output);
final JFileChooser fchooser = new JFileChooser(".");
int retvalue = fchooser.showSaveDialog(RectangleLabel.this);
if (retvalue == JFileChooser.APPROVE_OPTION)
{
fchooser.setSelectedFile(output);
File f = fchooser.getSelectedFile();
}
}
catch(IOException ie)
{
}
}
First, you need to create an image of the component...
BufferedImage img = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
label.printAll(g2d);
g2d.dispose();
Then you need to save it...
ImageIO.write(img, "png", f);
Take a look at Writing/Saving an Image for more details
Related
I am currently working with PNG images and I'm little bit blocked because a task that not sure how to fix...
This is the scenario. I have a PNG file of 655x265 pixels with a barcode inside of it. What I need to do is 'extend' the width of the image just to include a blank zone on the left of the image, just like this:
The problem is that nothing happens with the image dimensions when I execute my code:
public static void main(String[] args)
{
try
{
String path = "C:\\Users\\xxx\\Desktop\\a.png";
BufferedImage image = ImageIO.read(new File(path));
resizeImage(path, image.getWidth() + 100, image.getHeight());
Graphics graphics = image.getGraphics();
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Verdana", Font.PLAIN, 40));
graphics.drawString("TTT", 5, 250);
graphics.dispose();
ImageIO.write(image, "png", new File(path));
System.out.println("Image created");
} catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Fin");
}
public static void resizeImage(String path, int newHeight, int newWidth) throws IOException
{
File inputFile = new File(path);
BufferedImage inputImage = ImageIO.read(inputFile);
BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
Graphics2D graphics = outputImage.createGraphics();
graphics.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
graphics.dispose();
ImageIO.write(outputImage, "png", new File(path));
inputImage.flush();
outputImage.flush();
}
Do you know what I am doing wrong? Is one of my first times working with image files and probably I misunderstood something important...
Edit: Solution provides in the comments. Link
What you could do is let the method take a BufferedImage, resize it and return it:
public static BufferedImage resizeImage(BufferedImage inputImage, int newHeight, int newWidth){
BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
Graphics2D graphics = outputImage.createGraphics();
graphics.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
graphics.dispose();
outputImage.flush();
return outputImage;
}
Then continue working on the resized image in your surrounding method:
String path = "C:\\Users\\xxx\\Desktop\\a.png";
BufferedImage image = ImageIO.read(new File(path));
image = resizeImage(image, image.getWidth() + 100, image.getHeight()); // here you replace the image with the new, resized image from your method
Graphics graphics = image.getGraphics();
graphics.setColor(Color.BLACK);
....
I'm just new at java development, i can insert image into database by using file chooser and then convert to byte,the problem is i want to save a default image into database without using file chooser.I set the label with a specific image through properties.Can i convert the default image i set to label?
any help will be appreciated.
Yes, it's possible. You need to convert the Icon from the JLabel to BufferedImage, from there you can simply pass it through the ImageIO API to get a byte[] array
Icon icon = null;
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
try {
ImageIO.write(img, "png", ios);
// Set a flag to indicate that the write was successful
} finally {
ios.close();
}
byte[] bytes = baos.toByteArray();
} catch (IOException ex) {
ex.printStackTrace();
}
my project part code:
..........
BufferedImage bfi = getBufferedImage(iconToImage(my_Jlabel.getIcon()));
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageIO.write(bfi, "png", bs);
byte[] byteArray = bs.toByteArray();
pstmt.setBytes(17, byteArray);
.............
public static BufferedImage getBufferedImage(Image img){
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
BufferedImage bimage = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
return bimage;
}
static Image iconToImage(Icon icon) {
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
}
else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
I want to resize the an image from an URL to 50x50 px.
This is how i load the image:
jLabel1.setIcon(new javax.swing.ImageIcon(new URL("http://url.com/picture.jpg")));
How can i make picture.jpg 50x50px ?
Any ideas?
ImageIcon has a getImage() method, returning an Image.
Image has a getScaledInstance() method, returning a scaled Image.
ImageIcon has a constructor taking an Image as argument.
I'll let you assemble the 3-pieces puzzle.
You could try something like this:
public BufferedImage resize(final URL url, final Dimension size) throws IOException{
final BufferedImage image = ImageIO.read(url);
final BufferedImage resized = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = resized.createGraphics();
g.drawImage(image, 0, 0, size.width, size.height, null);
g.dispose();
return resized;
}
Usage:
final BufferedImage image = resize(new URL("http://url.com/picture.jpg"), new Dimension(50, 50));
I'm trying to do a small image processing with Java. The user should be able to load an image and add some easy modifications to the image by clicking a button.
Loading and displaying the image is no problem but when I try to make a binary image out of it the repaint() method makes me a black image on the screen.
I think the problem is with the repaint()-method. I already used the search function and Google but I still have no idea what's wrong in my code.
That's what I have so far:
public class ImageProcessing extends JFrame implements ActionListener {
private JPanel imagePanel;
private JPanel buttonPanel;
private JButton binaryButton;
private JButton loadButton;
private BufferedImage image;
private final String WINDOW_TITLE = "Image Processing";
public ImageProcessing() {
createWindow();
}
private void createWindow() {
this.setTitle(WINDOW_TITLE);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
imagePanel = new ImagePanel();
buttonPanel = new JPanel();
this.add(imagePanel, BorderLayout.CENTER);
loadButton = new JButton("Load image");
loadButton.addActionListener(this);
buttonPanel.add(loadButton);
this.add(buttonPanel, BorderLayout.SOUTH);
binaryButton = new JButton("binary");
binaryButton.addActionListener(this);
buttonPanel.add(binaryButton);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.loadButton) {
String filePath = getImageFile();
if (filePath != null) {
try {
image = ImageIO.read(new File(filePath));
// imageBackup = image;
} catch (IOException e1) {
e1.printStackTrace();
}
this.repaint();
}
} else if (e.getSource() == this.binaryButton) {
image = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
imagePanel = new ImagePanel();
this.repaint();
}
}
private String getImageFile() {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
File file = null;
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
return file.getPath();
} else
return null;
}
class ImagePanel extends JPanel {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
}
I hope you can help me and explain what I'm doing wrong. Thanks in advance.
It's not clear what kind of image processing you're trying to do. The code..
image = new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
..merely creates a new (blank) image with the byte binary type. You haven't drawn anything into it. That's why it's black.
To draw into it (for example to try to copy the original image), you can get a graphics context:
Graphics2D g = image.createGraphics();
And then copy with something like:
g.drawImage(otherImage, 0, 0, this);
I'm not sure whether or how Java will do a conversion from a full depth RGB image to TYPE_BYTE_BINARY. You might get an exception.
You are replacing the image panel instead of the image. Also, you're not performing the actual painting on the binary image. Here is an example how to convert the original image to a binary, it is based on the provided code:
else if (e.getSource() == this.binaryButton) {
BufferedImage mask = new BufferedImage(image.getWidth(),
image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
Graphics g = mask.getGraphics();
g.drawImage(image, 0, 0, this);
g.dispose();
image = mask;
this.repaint();
}
How do i save a resized image to a specific folder?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ImgChooser ic = new ImgChooser();
ImageIcon icon = new ImageIcon(me,"id pic");
Image img1 = icon.getImage();
Image img2 = img1.getScaledInstance(105, 105, 0);
icon.setImage(img2);
jLabel1.setIcon(icon);
}
This first code is where i get the image and resize it. Then i want the resized image to be saved in another folder. Thanks in advance
Use ImageIO.write(...) as others have already said (+1 to them), to add here is an example for you:
public static void main(String[] args) {
try {
BufferedImage originalImage = ImageIO.read(new File("c:\\test.jpg"));//change path to where file is located
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type, 100, 100);
ImageIO.write(resizeImageJpg, "jpg", new File("c:\\images\\testresized.jpg")); //change path where you want it saved
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
Reference:
http://www.mkyong.com/java/how-to-resize-an-image-in-java/
Try this...
Use ImageIO.write() method...
static boolean ImageIO.write(RenderedImage im, String formatName, File output) throws IOException
Eg:
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
First transform your image into a BufferedImage and then use ImageIO to save the image:
BufferedImage image = new BufferedImage(img2.getWidth(null), img2.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img2, 0, 0, null);
g2.dispose();
ImageIO.write(image, formatName, outputFile);
Where the format name is a String like "jpg", "png" or "gif" and outputFile is the File to save the image to.
Also please note that if you are saving an image that doesn't support an alpha level (transparency) then the third parameter you pass to the BufferedImage constructor should be a 3 byte image like: BufferedImage.TYPE_3BYTE_BGR