I have transferred my code from a method (button press action) to a new class. Its function is to capture screen image (much like print screen) and saves it somewhere in the computer. (in this case, drive c) It displays the following error message:
java.io.FileNotFoundException: c:\z\1.jpg (The system cannot find the
path specified)
public class printScreen{
public static void main(String args[]) throws AWTException, IOException
{
Robot robot = new Robot();
Dimension a = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle(a);
BufferedImage img = robot.createScreenCapture(rect);
ImageIO.write(img, "jpg", new File("c:/z/1.jpg"));
ImageIO.write(img, "bmp", new File("c:/z/2.bmp"));
ImageIO.write(img, "png", new File("c:/z/3.png"));
}
}
Any thoughts? All help will greatly be appreciated! Thank you!
File f = new File("c:/z/1.jpg")
f.createNewFile();
ImageIO.write(img, "jpg", f);
Related
I can't load image into BufferedImage Object with new File() without full path of the image.
When i'm trying to load an image.png into BufferedImage Object with new File() I face to results:
Success - when I write the whole path (C://Users//benja//Desktop/...) it works fine
Fail - when i write the path of the image that i have imported into my project. Is there a way to make it work even if i'm using new File(...)?
public class PicturePanel extends JPanel {
BufferedImage image=null;
public PicturePanel() {
try {
image = ImageIO.read(new
/*Works fine with full path: */
File("C://Users//benjamin//Desktop//Pictures//whiteFish.png"));
/*fail - throw an exception: */
//image = ImageIO.read(new
File("//RandomThingsInGui/whiteFish.png"));
} catch (IOException e) { e.printStackTrace(); }
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0,0,500,250,null);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new PicturePanel());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);
}
What i need is to know if there is a way (and how) to load the image from an imported path (I mean from inside eclipse) or when I use new File(...) I must use full path.
thanks for helpers :)
Copy the 'whiteFish.png' file to the 'RandomThingsInGui' directory.
Can you try this?
try {
// AS-IS
//image = ImageIO.read(new File("//RandomThingsInGui/whiteFish.png"));
// TO-BE (replace '//' to '/')
image = ImageIO.read(new File("/RandomThingsInGui/whiteFish.png"));
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to get an automatic .png behind the Filename in the JFileChooser.
How can I accomplish that?
public class Capture {
public static BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB);
component.paint(image.getGraphics());
return image;
}
public static void getSaveSnapShot(Component component, String fileName) throws Exception {
BufferedImage img = getScreenShot(component);
JFileChooser jfc = new JFileChooser();
jfc.addChoosableFileFilter(new FileNameExtensionFilter("Image files",new String[] { "png" }));
int retVal = jfc.showSaveDialog(null);
if(retVal==JFileChooser.APPROVE_OPTION) {
File f = jfc.getSelectedFile();
String test = f.getAbsolutePath();
ImageIO.write(img,"png",new File(test));
}
}
}
Just check if the path ends with png. If not add it:
...
String test = f.getAbsolutePath();
if (!test.endsWith(".png")) {
test = test + ".png";
}
...
You also have the option to add a filter to allow only some kind of files.
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.pdf", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.txt", "txt"));
That can help if you want to be sure to not have corrupted file when adding manually their type.
I am trying to save a resized picture to the user's desktop but not sure how to do that.
Here's my code so far:
mi.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userhome = System.getProperty("user.home");
fileChooser = new JFileChooser(userhome + "\\Desktop");
fileChooser.setAutoscrolls(true);
switch (fileChooser.showOpenDialog(f)) {
case JFileChooser.APPROVE_OPTION:
BufferedImage img = null;
try {
img = ImageIO.read(fileChooser.getSelectedFile());
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = img.getScaledInstance(f.getWidth(),
f.getHeight(), Image.SCALE_SMOOTH);
path = new ImageIcon(dimg);
configProps.setProperty("Path", fileChooser
.getSelectedFile().getPath());
imBg.setIcon(path);
break;
}
}
});
The code above resizes the imaged selected to fit the size of the JFrame then sets it to the JLabel.
This all works well but I also want to output the file to a set location lets say to the users desktop to make it easier. I'm currently looking at output stream but can't quite get my head around it.
Any help would be great.
Get the current Icon from the JLabel...
Icon icon = imgBg.getIcon();
Paint the icon to a BufferedImage...
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
Save the image to a file...
ImageIO.write(img, "png", new File("ResizedIcon.png"));
(and yes, you could use a JFileChooser to pick the file location/name)
You should also take a look at this for better examples of scaling an image, this way, you could scale the BufferedImage to another BufferedImage and save the hassle of having to re-paint the Icon
You might also like to take a look at Writing/Saving an Image
This is a example which is about saving images from Web to the local.
package cn.test.net;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
//a url from web
URL url = new URL("http://img.hexun.com/2011-06-21/130726386.jpg");
//open
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//"GET"!
conn.setRequestMethod("GET");
//Timeout
conn.setConnectTimeout(5 * 1000);
//get data by InputStream
InputStream inStream = conn.getInputStream();
//to the binary , to save
byte[] data = readInputStream(inStream);
//a file to save the image
File imageFile = new File("BeautyGirl.jpg");
FileOutputStream outStream = new FileOutputStream(imageFile);
//write into it
outStream.write(data);
//close the Stream
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
//every time read length,if -1 ,end
int len = 0;
//a Stream read from buffer
while( (len=inStream.read(buffer)) != -1 ){
//mid parameter for starting position
outStream.write(buffer, 0, len);
}
inStream.close();
//return data
return outStream.toByteArray();
}
}
Hope this is helpful to you!
I'm decoding an Qr Code that i'm getting throw the Java JSANE API. when i'm writing the image i got from the JSANE API in a file before reading it with IMAGEIO.read(), the decodong process is working but when i'm using the ilage Object given from the JSANE API directly without writing it in a file before reading, i' getting the following error :
Exception in thread "main" com.google.zxing.NotFoundException
The method i'm using are:
public String decode_QrCode(String filePath, String charset) throws FileNotFoundException, IOException, NotFoundException{
System.out.println("ICI ERREUR");
BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(new FileInputStream(filePath))
)
)
);
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap);
return qrCodeResult.getText();
}
public String decode_QrCode_buffImg(BufferedImage bufferedImage) throws NotFoundException{
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(
source
)
);
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap);
return qrCodeResult.getText();
}
I'm getting the image from the JSANE API like this:
Image image = dialog.openDialog();
I'm converting the Image to BufferedImage like this:
public static BufferedImage toBufferedImage(Image image)
{
if (image instanceof BufferedImage)
return (BufferedImage)image;
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha == true)
transparency = Transparency.BITMASK;
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) { } //No screen
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha == true) {type = BufferedImage.TYPE_INT_ARGB;}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
This the main function of the class:
public static void main(String[] args) throws IOException, cf, NotFoundException {
Frame frame = null;
// TODO Auto-generated method stub
JSaneDialog dialog = new JSaneDialog( JSaneDialog.CP_START_SANED_LOCALHOST,
frame, "JSaneDialog", true, null);
Image image = dialog.openDialog();
BufferedImage buffImg = toBufferedImage(image);
//BufferedImage buff = resize(buffImg, BufferedImage.TYPE_INT_RGB, buffImg.getWidth()/2, buffImg.getHeight()/2, 0.5, 0.5);
ImageIO.write(buffImg, "png", new File("/home/michaelyamsi/Bureau/Mémoires/test/test.png"));
QrCode New_Qr = new QrCode();
System.out.println("QR Code decompressed : " + New_Qr.decode_QrCode("/home/michaelyamsi/Bureau/Mémoires/test/test.png", "UTF-8"));
System.out.println("QR Code decompressed : " + New_Qr.decode_QrCode_buffImg(buffImg));
}
I'have even tried to resize th BufferedImage before using it but when i'm doing that, even the decode from the resultant file is not working.
The way I am saving a jFreeChart to a jpeg file is :
JFreeChart chart = ChartFactory.createXYLineChart(
"Hysteresis Plot", // chart title
"Pounds(lb)", // domain axis label
"Movement(inch)", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
Then:
image=chart.createBufferedImage( 300, 200);
The image appeas as:
My save function is:
public static void saveToFile(BufferedImage img)
throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("D:/Sample.jpg");
JPEGImageEncoder encoder2 =
JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam param2 =
encoder2.getDefaultJPEGEncodeParam(img);
param2.setQuality((float) 200, true);
encoder2.encode(img,param2);
fos.close();
}
I am calling it as:
try{
saveToFile(image);
}catch(Exception e){
e.printStackTrace();
}
The saved image appeas as:
Any suggestion, where I am wrong or how to save it the way it appears or may be I need to save as .png. Can anyone let me know how to save as .png?
Thanks
A simple Solution:
public static void saveToFile(BufferedImage img)
throws FileNotFoundException, IOException
{
File outputfile = new File("D:\\Sample.png");
ImageIO.write(img, "png", outputfile);
}
Saved the image, the way it appears.
I would rather suggest that instead of using ImageIo.write in order to save your image, you better use the following function:
ChartUtilities.saveChartAsJPEG("name of your file", jfreechart, lenght, width);
Because then you can manage the size of the picture but also save picture without filters.
Here is a great example on how this could be done.
File imageFile = new File("C:\\LineChart.png");
int width = 640;
int height = 480;
try {
ChartUtilities.saveChartAsPNG(imageFile, chart, width, height);
} catch (IOException ex) {
System.err.println(ex);
}