I'm writing a code which generate barcode in Image then display this image in label in my form then I want to print this barcode so I wrote this code
Icon icon = lbl.getIcon();
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphic = bi.createGraphics();
try {
lbl.printAll(graphic);
JOptionPane.showmessage(null, "success");
g.dispose();
} catch(Exception ex) {
JOptionPane.showmessage(null, "Error While Printing : " + ex.getMessage());
}
but I can't try it because I don't have printer, so this code will run correctly or any updates ?
Related
I have code to convert pptx slide into image and display the image in swing panel.
When i run my code in eclipse, it takes 10 Sec to display the panel whereas same code run via jar, it takes more than one minute to open the panel.
It happens only when user open it first time, Later it loads faster.
Any help would be appreciated and thanks in advance.
Here i included the code
// currentPage - Slide number to display
// source - pptx file path
public void Display(int currentPage, String source) {
try {
FileInputStream is = new FileInputStream(source);
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
double zoom = 1; // magnify it by 2
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = ppt.getPageSize();
XSLFSlide[] slides = ppt.getSlides();
all = slides.length;
lblPage.setText(currentPage + " / " + all);
current = currentPage;
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.transform(at);
graphics.setColor(Color.white);
graphics.clearRect(0, 0, pgsize.width, pgsize.height);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
System.out.println("Before draw: " + new Date());
slides[currentPage - 1].draw(graphics);
System.out.println("After draw: " + new Date());
// save the output
Image newImg = img.getScaledInstance(lblPresentasi.getWidth(), lblPresentasi.getHeight(), Image.SCALE_SMOOTH);
final ImageIcon icon = new ImageIcon(newImg);
lblPresentasi.setIcon(icon);
lblPresentasi.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
JLabel label = (JLabel) e.getComponent();
Dimension size = label.getSize();
Image resized = icon.getImage().getScaledInstance(size.width-10, size.height-10, Image.SCALE_FAST);
label.setIcon(new ImageIcon(resized));
}
});
graphics.dispose();
newImg.flush();
} catch (Exception e) {
e.printStackTrace();
}
}// end of method Display()
This delay was caused by One-Jar custom class loader. At first time, it takes more time to load the dependency libraries and load it classes.
So, I removed one-jar and using JarSplice to load the dependency libraries classes , it works great.
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
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)));
I am writing a code to make an image file of a chart appearing on a panel. For that purpose I create the buffered image of that and then use ImageIO.write(). It works but it only displays the panel(grey coloured panel) but does not show the chart present on that panel. What to do in this case?? Here is my code
com.objectplanet.chart.NonFlickerPanel p =
new com.objectplanet.chart.NonFlickerPanel(new BorderLayout());
p.add("Center", chart); // this statements adds the chart in the center of the panel
ChartPanel.add("Center", p);
ChartPanel.setSize(500, 200);
ChartPanel.show();
int w = ChartPanel.getWidth();
int h = ChartPanel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
ChartPanel.paint(g);
ChartPanel.printAll(g);
File f = new File("D:\\image.png");
try {
// png is an image format (like gif or jpg)
ImageIO.write(bi, "png", f);
} catch (IOException ex) {
ex.printStackTrace();
}
Well i solved the problem .Anyone facing the same problem ,here is the solution
Use paintall function rather than just paint function
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;
}