Display Image from bean - image

I have a bean with access to a image as byte[] here in the getImage method i convert a awt image to the byte array
public byte[] getImage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInByte = null;
try {
ImageIO.write( (BufferedImage)image, "jpg", baos );
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
return imageInByte;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageInByte;
}
I need to display the image with jsp within a table
like:
<table>
<c:forEach items="${beans}" var="bean">
<tr>
<td>${bean.name}</td>
<td>${bean.origin}</td>
<td>${bean.year}</td>
<td>${bean.number}</td>
<td>${bean.image}</td>
</tr>
</c:forEach>
Has it something to do with content type?

Create a img tag in your jsp file with src point to a servlet which will return the image byte array as a jpg image. You have to set correct mime type for the servlet output stream. One problem with this approach is that you have to save your image array in session for the servlet to pick it up.

Related

HtmlUnit Save Image Quality

I'm creating code to download some images from the web using HtmlUnit.
But when I save the image with HtmlUnit the quality of the image is very low compared with the original image.
I used this code to save the img url to a file.
try {
HtmlImage imgX = (HtmlImage)
page.getByXPath("//img").get(0);
Thread.sleep(3000);
File imageFile = new File(dir +"/"+ name);
imgX.saveAs(imageFile);
System.out.println("Done!!!!");
} catch (Exception e) {
e.printStackTrace();
}
Are there other options to get the image with the best quality?
I tried using this:
How to convert an <img... in html to byte [] in Java
But the image was not created.
Get the WebResponse from HtmlImage:
InputStream inputStream = imgX.getWebResponse(true).getContentAsStream();
And then work directly on InputStream:
File imageFile = new File(dir +"/"+ Name);
FileOutputStream outputStream = new FileOutputStream(imageFile);
IOUtils.copy(inputStream, outputStream);

getting image path in jsp

in my project I have to upload the image and show it in user profile view . Now I am successfully storing , I have problem in displaying image. the image is stored path D:/uploads so my image retrieving code in jsp is,
<c:set var="fileanme2" value="${teacherId.getPhoto()}"></c:set>
<%
String uploadFilePath2 = "D:" + "/" + "uploads";
%>
<c:set var="shlash2" value="/"></c:set>
<c:set var="pathValue2" value="<%=uploadFilePath2%>"></c:set>
<c:set var="string4" value="${pathValue2}${shlash2}${fileanme2}" />
<img alt="Image" src="${string4}" width="160" height="160"
class="img-thumbnail">
But image is not displaying , when I inspect the image element in browser in src attrib it showing path as D:/uploads/img when I hover mouse on it shows the path along with the project path how can I get the exact path for displaying image.
no need of any string concatenation and any extra work, you can do it in one line:
<c:set var="filePath" value="D:/uploads/${teacherId.getPhoto()}" />
and solutions for your problem:
1) if you are going to show image from you local file system then do like:
<img src="file:///D|/uploads/image_name.jpg"
width="200"
height="200"
alt="Image"/>
Warning: image may not be accessible when you publish your site.
2) create a servlet to handle GET request's of all images by passing name of image in url like:
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("getting photo...");
String imageName = request.getParameter("imageName");
System.out.println("imageName: "+imageName);
//set your upload path
File imageFile = new File("D:\\uploads\\"+imageName);
System.out.println("file exists: "+imageFile.exists());
// Get content type by filename.
String contentType = getServletContext().getMimeType(imageFile.getName());
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(imageFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + imageFile.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(imageFile), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
close(output);
close(input);
}
// Check if file is actually an image (avoid download of other files by hackers!).
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
if (contentType == null || !contentType.startsWith("image")) {
// Do your thing if the file appears not being a real image.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
}
// Helpers (can be refactored to public utility class)
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
}
and then in jsp use img tag like:
<img alt="Image"
src="<c:url value="/ImageServlet?imageName=${teacherId.getPhoto()}"/>" />
Source: BalusC image servlet

Mixing JSON data and image content in a single HTTP response

Is it possible to include multiple response types in a single HTTP response? For example, JSON data as well as an image.
Hey It is not possible to set multiple MIME TYPE to HTTPResponse. But what you can do is, you can set the content type as application/json. And using json you can send the image using BASEEncoder.
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
No. I think one generally would send the URL of image in json, and use javascript to update the "src" attribute of "img" element

Primefaces Print Dynamic Images

I tried to load an image dynamically, and everything works.
The image I is loaded and displayed correctly in a dynamic,
I added the tag for printing.
Now if I ask to print the image created dynamically I can not print.
<pou:commandButton value="Print" type="button" icon="ui-icon-print">
<pou:printer target="image" />
</pou:commandButton>
<pou:graphicImage id="image" value="#{printDynamicBean.graphicIMG}" />
My bean does like this:
public StreamedContent getGraphicIMG() {
//Graphic
BufferedImage bufferedImg;
try {
bufferedImg = ImageIO.read(baseImage);
} catch (IOException e) {
}
try {
Graphics2D g2 = bufferedImg.createGraphics();
g2.setColor(Color.black);
int style = Font.BOLD | Font.ITALIC;
Font f1 = new Font("TimesNewRoman", style , 60);
g2.setFont(f1);
g2.drawString("Hello Print", 80, 580);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
graphicIMG = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
} catch (IOException ex) {
Logger.getLogger(PrintCartelliniBean.class.getName()).log(Level.SEVERE, null, ex);
}
return graphicIMG;
}
it is as if she had forgotten the image created.
Thanks.
using CDI bean you can do this :
#Model
public class ImageBean {
private StreamedContent image;
#Produces
#Named
public StreamedContent getImage() {
if (FacesContext.getCurrentInstance().getRenderResponse()) {
// rendering the view, return a stub StreamedContent to generate right URL.
image = new DefaultStreamedContent();
} else {
// requesting the image
image = your dynamic image;
}
return image;
}
}
in your view : <pou:graphicImage id="image" value="#{image}" />

Passing Image between servers for remote saving

My Spring application passes image file to Jersey application to get rid of all image manipulation tasks.
On receiving image, the Jersey application should save the image after several manipulations (crop, resize etc) and return image url.
For this, the Spring application has the below form in a JSP file:
<form method="POST" action="/asdf" enctype="multipart/form-data">
<input type="file" name="fstream"></input>
<input type="submit" value="Upload"/>
</form>
In my spring controller, I get DataInputString using:
DataInputStream in = new DataInputStream(request.getInputStream());
What would be an easy approach to carry out the desired action mentioned above?
How about converting it to BufferedImage in Spring app, POST it to the Jersey app, carry out required manipulations and save the image?
If that's fine, how do I convert DataInputStream to BufferedImage?
Thanks in advance.
Since there was no answer ...
I obtained byte array from submitted form data
Sent an object with byte[] being one of the attribute to REST server
On server side, I converted byte[] to BufferedImage which I scaled (using ImgScalr API) as required, and saved it.
#Path("/image")
public class ImageController {
#PUT
#Path("upload/{fileName}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response upload(#PathParam("fileName") String fileName, FileBytes fileBytes){
byte[] bytearray = fileBytes.getFileBytes();
int len = bytearray.length;
if(len>0){
try {
int width=0, height=0, edge=0, px1=0, px2=0;
InputStream in = new ByteArrayInputStream(bytearray);
BufferedImage image = ImageIO.read(in);
File file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_ORIGINAL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving original image
width = image.getWidth();
height = image.getHeight();
//scaling as required
if(height>width){
px2 = (height-width)/2+1;
edge = width;
}else if(width>height){
px1 = (width-height)/2+1;
edge = height;
}else{
edge = width;
}
//using ImgScalr API to get scaled image
image = image.getSubimage(px1, px2, edge, edge);
image = Scalr.resize(image, 120);
file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_THUMBNAIL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving scaled image
} catch (Exception e) {
e.printStackTrace();
}
}
return Response.status(Status.OK).entity("Filename:"+fileName).build();
}
}

Resources