Getting Path of File Inside Jar - java

I'm trying to access an image located inside of a running jar.
Here is my code:
Image image = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/res/sprites/"));
The code above works absolutely fine.
The problem I'm having is a is converting it into a readable String to be used by a BufferedImage objet.
Here is my code: (pathRelativeToThis is a String)
Image path = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/res/sprites/" + pathRelativeToThis));
String image = "file://" + path.toString();
URL url = new URL(image);
BufferedImage img = ImageIO.read(url);
This doesn't work and gives javax.imageio.IIOException: Can't get input stream from URL! as an error.
What is the correct way to do this?

You can do it like this and work with stream directly:
InputStream is = getClass().getResourceAsStream("/res/sprites/" + pathRelativeToThis);
BufferedImage img = ImageIO.read(is);
is.close();
Also have you tried to pass resource URL to ImageIO directly?
URL url = getClass().getResource("/res/sprites/" + pathRelativeToThis)
BufferedImage img = ImageIO.read(url);

Remove path and just try to do this
String image = "file://" + getClass().getResource("/res/sprites/" + pathRelativeToThis);
URL url = new URL(image);
BufferedImage img = ImageIO.read(url);

Related

CanĀ“t get absoluteX and absoluteY from image using itext

I try to get a image (jpg format) from url to put in my pdf using itext 5.0.5 with this simple code below:
Image imageToShow = null;
imageToShow = Image.getInstance(new URL("any image url here"));
imageToShow.scaleAbsolute(size[0], size[1]);
I get the image but the value from absoluteX and absoluteY is always a 'NaN' value and this problem prevents me to change this values (third line), what I'm doing wrong?
If you are in a situation where you can switch to another iText version, try out iText7.
The equivalent code would be:
// src url
String somePath = "https://www.pdfa.org/wp-content/uploads/2016/08/ITSC-Logo-Horizontal-RGB-300dpi.png";
// fetch image data
ImageData imageData = ImageDataFactory.create(new URL(somePath));
// turn into image object
Image image = new Image(imageData);
// perform scaling operation
image = image.scaleAbsolute(120f, 120f);
// debug
System.out.println(image.getImageWidth() + "x" + image.getImageHeight());

Error in resizing Image with the width of the label Java 8.0

Hi Guys I'm having issue in my Image, I just want to resize the image w/ my label. By using the filechooser. Here is the code below.
try {
File file = jfc.getSelectedFile();
java.net.URL url = file.toURL();
BufferedImage imageBuf = null;
BufferedImage imageSize = null;
try {
imageBuf = ImageIO.read(url);
imageSize = (BufferedImage) imageBuf.getScaledInstance(jlbl_image.getWidth(), jlbl_image.getHeight(),Image.SCALE_SMOOTH);
ImageIcon img;
img = new ImageIcon(imageSize);
jlbl_image.setIcon(img);
} catch (IOException ex) {
Logger.getLogger(JFRecordSection.class.getName()).log(Level.SEVERE, null, ex);
}
Here is the error code when I load the image from fileChooser.
sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
The error message is telling you exactly what the problem is: your image is not a BufferedImage, and so it shouldn't be treated as one. Your assumption is incorrect, however. It's not a that the image loaded from the JFileChooser isn't a BufferedImage, rather it's the scaled image returned from the .getScaledInstance(...) that isn't. So instead cast it to the interface type, Image, and you should be able to use it.

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.

Converting BMP to Gif

I need help to convert a .BMP image to .gif .
I am struggling with preserving the quality of the the converted gif image. I need help here . Following is the related code. Any help is appreciated.
//now Convert the names to lower case and change the extension to the file as a .gif file under the images directory
//you can either use URL or File for reading image using ImageIO
bufferedSourceImg = ImageIO.read(fSource);
//getting the RGB mode color value
int color = bufferedSourceImg.getRGB(0,0);
Image image = makeColorTransparent(bufferedSourceImg,new Color(color));
//getting the transparent image
BufferedImage transparent = imageToBufferedImage(image);
//generating the name of the gif image which will be created from the bmp
int idx = destFName.lastIndexOf(".");
destFName = destFName.substring(0, idx);
destFName = destFName + ".gif";
gifFile = new File(getImagesDirectory(), destFName);
//copying the gif copy of the image
Iterator itr = ImageIO.getImageWritersByFormatName("gif");
ImageWriter gifWriter = (ImageWriter)itr.next();
ImageWriteParam iwp = gifWriter.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
String compTypes[] = iwp.getCompressionTypes();
iwp.setCompressionType(compTypes[compTypes.length - 1]);
iwp.setCompressionQuality(0);
//ImageIO.write(transparent, "gif", gifFile);
ImageIO.write(bufferedSourceImg, "gif", gifFile);
FileImageOutputStream output = new FileImageOutputStream(gifFile);
gifWriter.setOutput(output);
IIOImage iioImage = new IIOImage(transparent, null, null);
gifWriter.write(null, iioImage, iwp);
gifWriter.dispose();

Categories