Display image on web using spring and apache common from folder - java

In my application i have a uploaded functionality.For that i have used apache-commons file upload and spring multipart and i have stored the image in directory folder(not within project context).
The problem where i stuck is fetching the image and rendering it on the jsp.I tried to read the image from that folder using Buffered image and ImageIO but can't figured out how to render it in jsp using img tag.
Any help would be appreciated.
//Code for reading
BufferedImage im=ImageIO.read(new File(imagePath));

Finally able to display the image on web browser using img tag.
Step that i follow now :
1. I read the image using BufferedImage.
2.Converted the bufferedImage into byte using ByteArrayOutputStream.
3.Encoded that stream into Base64 using apache commons codec lib and coverted into string
4.Returned this string value of image on html using img tag
//Pseudo Code
BufferedImage bufferedImage=ImageIO.read(new File(imagePath));
//imageDao contains the image name that i stored in the database
String []formatSplit=imageDao.split("\\.");
if(formatSplit.length==2){
String format=formatSplit[1];
//ImageUtility is class that contain code for converting bufferedimage to string
String traineeImage=ImageUtility.encodeToString(bufferedImage,format );
model.addAttribute("imagePath", traineeImage);
}
//ImageUtilty class -method
public static String encodeToString(BufferedImage image, String type) {
String imageString=null;
String encodedImage=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
encodedImage=org.apache.commons.codec.binary.Base64.encodeBase64String(imageBytes);
imageString = "data:image/"+type+";base64,"+encodedImage;
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
And in the img tag src attribute i passed imageString and it worked.
For finding the solution lot of hint i found from stackoverflow and from other blog that helped me to achieve what i was looking for.
Thanks.

Related

How to get svg in database injava

I am having 1 problem. I save SVG images in the database as binary. Now, I want to download it without converting to base64, is there any way. Thank you.
Basically, that would mean getting the BLOB object from the database.
I would follow this approach to show it in directly in the browser:
#RestController
public class ImageController {
#GetMapping(value = "/img-test", produces = "image/svg+xml")
public byte[] getImg() throws IOException
{
// retrieve your image from the DB
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
return inp.readAllBytes(); // This is a Java 9 specific convertion
}
}
With this approach, you do not change anything on the BLOB image. You take it and return it as is, an array with bytes. And you can directly show it in a browser or embed it somewhere in your HTML file.
The main thing here is the MIME type : image/svg+xml
If you are using an older version of Java, then check this question for the conversion of the InputStream object to a byte array.
And with this approach you can download the file:
#GetMapping("download-img")
public ResponseEntity downloadImg() throws IOException
{
// Get the file from the DB...
File imgFile = new File("C:\\Users\\USR\\Desktop\\img.svg");
InputStream inp = new DataInputStream(new FileInputStream(imgFile));
//Dynamically change the File Name here
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"img.svg\"")
.body(inp.readAllBytes());
}

Input image not getting read in java with getResource

I'm trying to add image of user's selection to my pdf generated through pdfbox in netbeans. If i directly give path to directly then it's working but with getting url of image path and adding that doesn't work.
See the given code problem is with URL and Path, Because input isn't getting read
public static ByteArrayOutputStream PDFGenerator(........,Path imagespath)
{
........
if (finalpdf.Images != null)
{
Path imagepath = Paths.get(imagespath.toString(), "room.png");
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath.toString(), pdf);
AddImages(content, Addedimage, 229.14f, 9.36f);
}
//AddImages method is following
public static void AddImages(PDPageContentStream content, PDImageXObject image, float x, float y) throws IOException
{
content.drawImage(image, x, y);
}
}
//Following is snippet from my test method
public void testClass()
{
........
finalpdf.Images = "room.png";
URL imageurl = testclass.class.getResource("room.png");
Path imagepath = Paths.get(imageurl.getPath().substring(1));
ByteArrayOutputStream baos = PDFGenerator.generatefurtherpdf(finalpdf, "0000.00", "00.00", imagepath);
writePDF(baos, "YourPdf.pdf");
}
I expect that it works this way but i'm sure its some problem with Path, I'm not using this correctly. I hope the code is explanatory enough as i'm quite new also there are security reasons so I can't put the whole code. Sorry for mistakes
For resources (never a File) there exists a generalized class: Path.
Path path = Paths.get(imageurl.toURI());
However whenever that path (for instance with an URL ´jar:file//... .jar!... ... .png") will be used as File, which an path.toString() suggests, one can use an InputStream.
The second generalized class is an InputStream which is more low-level:
InputStream in = TestClass.getResourceAsStream(imagepath);
This is a short-cut for the never used getResource().openStream(). Throwing a NullPointerException when the resource path is incorrect.
The last ressort is to use the actual byte[] for createFromByteArray.
byte[] bytes = Files.readAllBytes(path);
PDImageXObject Addedimage = PDImageXObject.createFromByteArray(doc, bytes, name);
Using a temporary file
Path imagepath2 = Files.createTempFile("room", ".png");
Files.copy(imagepath, imagepath2);
PDImageXObject Addedimage = PDImageXObject.createFromFile(imagepath2.toString(), pdf);

How to create a JavaFX Image from an absolute path?

I have an instantiated File object. I know it contains a picture format. I don't know where on the system the file is placed, other than the methods of File available to me getPath(), getAbsolutePath() etc.
My question is: how can I instantiate a JavaFX Image object with the picture in my File?
File provides a method to retrieve the URL for the file and the Image constructor expects a URL String.
Image imageForFile = new Image(file.toURI().toURL().toExternalForm());
Combining the javax.imageio.ImageIO class (ref) and the javafx.embed.swing.SwingFXUtils (ref) can convert an "input" (i.e.: stream, file, URL) to a JavaFX image. Sample code (for File):
public static Image readImage(File file) {
try {
BufferedImage bimg = ImageIO.read(file);
return SwingFXUtils.toFXImage(bimg, null);
}
catch( IOException e ) {
// do something, probably throw some kind of RuntimeException
}
}

Loading image from a resource Can't read input file

I am trying to load a resource image, but I am getting an error that says:
javax.imageio.IIOException: Can't read input file!
if(full.equals("")){
try{
full = HomePage.class.getResource("/images/default.jpg").getPath();
System.out.println(full);
File imgPath = new File(full);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data = (DataBufferByte)raster.getDataBuffer();
full = "data:image/jpeg;base64," + DatatypeConverter.printBase64Binary(data.getData());
}catch(IOException ex){
Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I print out the variable full, I get the following location:
file:/C:/Users/rnaddy/Documents/NetBeansProjects/Phantom%20Browser/dist/run1534966744/Phantom_Browser.jar!/images/default.jpg
So, what am I doing wrong?
ImageIO knows how to read from jar files, so you can just say
BufferedImage bufferedImage = ImageIO.read(HomePage.class.getResource("/images/default.jpg"));
As for why your solution doesn't work, getResource returns a URL. If you print it out when you run your application through the jar, you'll see that it returns jar:file:/path/to/file for the resource, whereas if you ran getPath and printed that out, you'll see file:/path/to/file.
Presumably, ImageIO will handle the input differently depending on what kind of URL you pass in.

ImageIO can't read input file

public static void imRes(String pat) {
try {
BufferedImage bckimg = ImageIO.read(new File("c:/s/deneme.jpg"));
File s = new File(pat);
BufferedImage im = ImageIO.read(s);
BufferedImage im1 = resIm(im);
BufferedImage finIm = mergIm(im1, bckimg);
ImageIO.write(finIm, "jpg", new File("c:/s/deneme1.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
This is my first post, excuse me if I've done something wrong. This code was running properly untill i try to read an image from the source package. But now it can't read any image. What am I doing wrong? Or is it something about eclipse?
Exception:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at imRe.imRes(imRe.java:12)
at imReTest.main(imReTest.java:6)
Thanks...
Change / for \ if you are using windows.
A more cross-platform approach would be substitute
C: for File.listRoots()[0] and every / for File.separator.
Read more on the File api documentation
EDIT
(I didn't read this line, sorry)
This code was running properly untill i try to read an image from the source package
In order to get a file from inside your jar package, one must use the getClass().getResource() method.
Example:
application-package:
|-Main.java
|-resources
|-image.jpg
For the above directory structure:
BufferedImage im = ImageIO.read(new File(getClass().getResource("/resources/image.jpg").toURI()));
Would do the trick.

Categories

Resources