Forcing ".png" in JFileChooser Save Dialog - java

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.

Related

How to save an image in a set location?

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!

WritableRaster java

I working on "mini photoshop" in java. I open jpg file useing this method
public BufferedImage open()
{
fc = new JFileChooser();
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION)
{
try {
img=ImageIO.read(fc.getSelectedFile());
img2=ImageIO.read(fc.getSelectedFile());
raster = img.getRaster();
} catch (IOException e) {
e.printStackTrace();
}
}else
img = null;
return img;
}
In this picture I make some change eg. sephia, sobel. But after this I want back to origin picture, I use for this method to do this:
public BufferedImage origin() {
raster=img.getRaster();
return img2;
}
The problem arises when I want again use sepia or any other filter because program remember earlier modification.
For example when i use sepia then back to origin and use sobel, program show me sepia+sobel, should show only sobel.
Should the below line
raster=img.getRaster();
change to
raster=img2.getRaster(); ?
public BufferedImage origin() {
raster=img.getRaster();
return img2;
}

Screen capture using codes

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);

Saving an image to .jpg file : Java

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);
}

How to rescale and save an BufferedImage

I got a BufferedImage and want to rescale it before saving it as an jpg/png.
I got the following code:
private BufferedImage rescaleTo(BufferedImage img,int minWidth,int minHeight) {
BufferedImage buf = toBufferedImage(img.getScaledInstance(minWidth, minHeight, Image.SCALE_DEFAULT));
BufferedImage ret = new BufferedImage(buf.getWidth(null),buf.getHeight(null),BufferedImage.TYPE_INT_ARGB);
return ret;
}
public BufferedImage toBufferedImage(Image img) {
BufferedImage ret = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = ret.createGraphics();
g2.drawImage(img,0,0,null);
return ret;
}
public String saveTo(BufferedImage image,String URI) throws UtilityException {
try {
if(image == null)
System.out.println("dododod");
ImageIO.write(image, _type, new File(URI));
} catch (IOException e) {
throw new UtilityException(e.getLocalizedMessage());
}
return URI;
}
But as an result I just get a black picture. It must have to do with the rescaling as when I skip it I can save the expected picture.
As a test, set _type="png" and also use file extension .png when you make the call to ImageIO.write(image, _type, new File(URI));. I had issues like you describe and I started writing type PNG and all works fine. Unfortunately, I never went back to debug why I could not write type JPG, GIF etc.

Categories