How can i make .png my default file extension in java - java

Here is the snippet where i save the image with a .png extension:
WritableImage img = rectCanvas.snapshot(new SnapshotParameters(), null);
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = chooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File fileToSave = chooser.getSelectedFile();
ImageIO.write(SwingFXUtils.fromFXImage(img, null), "png", fileToSave);
} catch (IOException ex) {
Logger.getLogger(GuiClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
I want .png to be my default file extension. However when i want to save an image to file and open the save dialog i have to enter the file name in the following format: filename.png. How can i get rid of the .png part and make it default?

What are you setting as the value of "fileToSave"? If that isn't .png, it shouldn't be a png extension.
See the following from oracle's documentation:
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}

Related

Loading pictures from Filechooser

My code:
try {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG", "*.png"));
File file = fileChooser.showOpenDialog(null);
BufferedImage originalImage = ImageIO.read(new File(memberView.selectedPicturePath.getText()));
ImageIO.write(originalImage, ".png", file.getAbsoluteFile());
} catch (IOException e) {
System.out.println(e.getMessage());
}
i want to save an image from a random directory to the one specified here but every time i get a Can't read input file! message.
The image i am trying to load actually exists since i am choosing it with the file loader.
Where is the problem in this code?
Check that what method memberView.selectedPicturePath.getText()) is return, perhaps it is not valid path to your image.

how to upload image in form using code netbeans

Am writing an ID CARD processing app in java but am having problem with the code that will upload and display a client image in a label i created for picture. the only thing am getting with the code below is the image path but not the image it self.
This is the code i have attempted so far.
FileFilter ff = new FileNameExtensionFilter("images","jpeg");
fc.addChoosableFileFilter(ff);
int open = fc.showOpenDialog(this);
if (open == javax.swing.JFileChooser.APPROVE_OPTION){
java.io.File path = fc.getSelectedFile();
String file_name = path.toString();
pathe.setText(file_name);
java.io.File image = fc.getSelectedFile();
ImageIcon photo = new ImageIcon(image.getAbsolutePath());
The code that does the magic is below
FileFilter ff = new FileNameExtensionFilter("images","jpeg");
fc.addChoosableFileFilter(ff);
int open = fc.showOpenDialog(this);
if (open == javax.swing.JFileChooser.APPROVE_OPTION){
java.io.File path = fc.getSelectedFile();
String file_name = path.toString();
pathe.setText(file_name);
BufferedImage bi; // bi is the object of the class BufferedImage
// Now you use try and catch `enter code here`
try{
bi = ImageIO.read(path); // path is your file or image path
jlabel.setIcon( new ImageIcon(bi));
}catch(IOException e){ }

FileNotFoundException when reading a BufferedImage

I'm trying to crop an image received from a form upload. Before I crop it I save it, then I retrieve it again as a BufferedImage (because I don't know how to turn a part into a buffered Image). I then crop this image, but when I try to save it again I get a java.io.FileNotFoundException (access denied)
The first image gets saved correctly, I get the exception when I try to pull it back.
Is it possible to turn my part into a buffered image and then save it? Instead of doing double work. or else is there some fix to my below code.
String savePath = "path";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
//functionality to ormit non images
String fileName = extractFileName(part);
part.write(savePath + "/" + fileName);
String imagePath = savePath + "/" + fileName;
BufferedImage img = null;
try {
img = ImageIO.read(new File(imagePath));
img = img.getSubimage(0, 0, 55, 55);
ImageIO.write(img, "jpg", fileSaveDir);
} catch (IOException e) {
System.out.println(e);
}
}
ImageIO.write((RenderedImage im, String formatName, File output));
Parameters:
im a RenderedImage to be written.
formatName a String containg the informal name of the format.
output a File to be written to.
As per documentation output file parameter is the file object where it would be image written where you have passed the parent directory file object.

Can I tell what the file type of a BufferedImage originally was?

In my code, I have a BufferedImage that was loaded with the ImageIO class like so:
BufferedImage image = ImageIO.read(new File (filePath);
Later on, I want to save it to a byte array, but the ImageIO.write method requires me to pick either a GIF, PNG, or JPG format to write my image as (as described in the tutorial here).
I want to pick the same file type as the original image. If the image was originally a GIF, I don't want the extra overhead of saving it as a PNG. But if the image was originally a PNG, I don't want to lose translucency and such by saving it as a JPG or GIF. Is there a way that I can determine from the BufferedImage what the original file format was?
I'm aware that I could simply parse the file path when I load the image to find the extension and just save it for later, but I'd ideally like a way to do it straight from the BufferedImage.
As #JarrodRoberson says, the BufferedImage has no "format" (i.e. no file format, it does have one of several pixel formats, or pixel "layouts"). I don't know Apache Tika, but I guess his solution would also work.
However, if you prefer using only ImageIO and not adding new dependencies to your project, you could write something like:
ImageInputStream input = ImageIO.createImageInputStream(new File(filePath));
try {
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(input);
BufferedImage image = reader.read(0); // Read the same image as ImageIO.read
// Do stuff with image...
// When done, either (1):
String format = reader.getFormatName(); // Get the format name for use later
if (!ImageIO.write(image, format, outputFileOrStream)) {
// ...handle not written
}
// (case 1 done)
// ...or (2):
ImageWriter writer = ImageIO.getImageWriter(reader); // Get best suitable writer
try {
ImageOutputStream output = ImageIO.createImageOutputStream(outputFileOrStream);
try {
writer.setOutput(output);
writer.write(image);
}
finally {
output.close();
}
}
finally {
writer.dispose();
}
// (case 2 done)
}
finally {
reader.dispose();
}
}
}
finally {
input.close();
}
BufferedImage does not have a "format"
Once the bytes have been translated into a BufferedImage the format of the source file is completely lost, the contents represent a raw byte array of the pixel information nothing more.
Solution
You should use the Tika library to determine the format from the original byte stream before the BufferedImage is created and not rely on file extensions which can be inaccurate.
One could encapsulate the BufferedImage and related data in class instance(s) like so:
final public class TGImage
{
public String naam;
public String filename;
public String extension;
public int layerIndex;
public Double scaleX;
public Double scaleY;
public Double rotation;
public String status;
public boolean excluded;
public BufferedImage image;
public ArrayList<String> history = new ArrayList<>(5);
public TGImage()
{
naam = "noname";
filename = "";
extension ="";
image = null;
scaleX = 0.0;
scaleY = 0.0;
rotation = 0.0;
status = "OK";
excluded = false;
layerIndex = 0;
addHistory("Created");
}
final public void addHistory(String str)
{
history.add(TGUtil.getCurrentTimeStampAsString() + " " + str);
}
}
and then use it like this:
public TGImage loadImage()
{
TGImage imgdat = new TGImage();
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif", "tif");
fc.setFileFilter(filter);
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fc.showOpenDialog(this); // show file chooser
if (result == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
System.out.println("Selected file extension is " + TGUtil.getFileExtension(file));
if (TGUtil.isAnImageFile(file))
{
//System.out.println("This is an Image File.");
try
{
imgdat.image = ImageIO.read(file);
imgdat.filename = file.getName();
imgdat.extension = TGUtil.getFileExtension(file);
info("image has been loaded from file:" + imgdat.filename);
} catch (IOException ex)
{
Logger.getLogger(TGImgPanel.class.getName()).log(Level.SEVERE, null, ex);
imgdat.image = null;
info("File not loaded IOexception: img is null");
}
} else
{
imgdat = null;
info("File not loaded: The requested file is not an image File.");
}
}
return imgdat;
}
Then you have everything relevant together in TGImage instance(s).
and perhaps use it in an imagelist like so:
ArrayList<TGImage> images = new ArrayList<>(5);

how to save the the image in folder on disk using java

I want to save the image on disk such as c:/images which is captured by webcam using java ..and again I want to display that image on JForm as a label...
is this possible using java and netbeans
I'm new in java
you can save image
private static void save(String fileName, String ext) {
File file = new File(fileName + "." + ext);
  BufferedImage image = toBufferedImage(file);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
and read image from disk and show into label as
File file = new File("image.gif");
image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
You can use BufferedImage to load an image from your hard disk :
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
Try this link for further information. Reading/Loading Images in Java
And this one for saving the image. Writing/Saving an Image
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
Pure Java, not third party library needed:
byte[] image = /*your image*/
String filePath = /*destination file path*/
File file = new File(filePath);
try (FileOutputStream fosFor = new FileOutputStream(file)) {
fosFor.write(image);
}
//Start Photo Upload with No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with No//

Categories