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){ }
Related
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) {
...
}
I use Apache Batik to preview svg documents in a jframe.
What I want to do is the user to give some Images (e.g. png or jpeg)
and then my program to turn them into svg documents.
Is this SVGCreator any possible?
FileChooser
JFileChooser fc = new JFileChooser(".");
int choice = fc.showOpenDialog(panel);
if(choice == JFileChooser.APPROVE_OPTION){
File f = fc.getSelectedFile();
String filepath = f.toURL().toString();
SVGDocument document = SVGCreator(filepath);
SVGViewer(document);
}
}
SVGViewer (extends JFrame)
public SVGViewer(SVGDocument document){
JSVCanvas canvas = new JSVCanvas();
this.getContentPane().add(canvas);
canvas.setSVGDocument(document);
this.pack();
this.setVisible(true);
}
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.
For my project, I am creating an expense management system. There is a place where the user can select an image file from local disk and add it as an attachment when adding a new expense.
The uploaded image should be displayed in a jLabel and then should be saved inside the project folder (say for e.g. /src/accounts/media) when clicking the save button, and the path should be saved inside a varchar column in mysql database for later retrieval.
For now, I can upload the image and display the image in jLabel.
Can anyone help me out on how save that image file inside a folder and to store the path in database?
JFileChooser chooser = new JFileChooser();
FileFilter ft = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
//FileFilter ft2 = new FileNameExtensionFilter("PDF Files", "pdf");
chooser.addChoosableFileFilter(ft);
//chooser.addChoosableFileFilter(ft2);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filePath = f.getAbsolutePath().toString();
BufferedImage img = null;
try {
img = ImageIO.read(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(lblAttachment.getWidth(), lblAttachment.getHeight(), Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(dimg);
lblAttachment.setText("");
lblAttachment.setIcon(icon);
To copy file to another location, you can choose any
Way1
Way2
To store the path, make a file-path column write insert query (SQL) :
prepareStatement ps = conn.prepareStatement("INSERT INTO filePath VALUES(?, ?, ?)" );
ps.setString(1,filePath);
ps.set..
// conn, connection object
Full tutorial Here
Edit:
To save it in you some default Resources folder, You can obtain path, for EG:
public class ClassDemo {
public static void main(String[] args) throws Exception {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
// finds resource relative to the class location
URL url = cls.getResource("file.txt");
System.out.println("Value = " + url);
// finds resource relative to the class location
url = cls.getResource("newfolder/a.txt");
System.out.println("Value = " + url);
}
}
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);