Passing Image between servers for remote saving - image

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();
}
}

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);

Displaying byte array as image; base64 data URI doesn't work above 32KB in IE

I have a image as byte[] in my bean. User can upload image using <h:inputFile/>. As soon as user clicks upload the image should be displayed in the page(Should not be saved in DB/Folder). I tried using Base64 convertion but in IE it's displaying only 32KB size image.
Below is my xhtml code.
<h:form id="signatureform" enctype="multipart/form-data">
<h:inputFile id="inputFile" label="file1" value="#{bean.part}"/>
<h:commandButton id="upButton" type="submit"
action="#{bean.uploadSignature}"
value="Upload" styleClass="commandButton">
</h:commandButton>
</h:form>
<h:graphicImage url="data:image/jpg;base64,#{bean.encodedImage}"
width="275px" height="75px"></h:graphicImage>
My Java code is
private String encodedImage ;
private Part part;
//getters and setters
public String uploadSignature() throws IOException {
InputStream inputStream = null;
try {
inputStream = part.getInputStream();
encodedImage = new String(Base64.encode(IOUtils.toByteArray(inputStream)));
} catch (Exception e) {
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return SUCCESS;
}
I have tried with <a4j:mediaOutput/> but no help. Please help me to resolve it.
Finall i was able to display my Image in IE. My requirement was to display an image in 275px *75px. For this requirement i resized my image in Java and displayed in the Web page. When i resized my image and converted to Base64 string it became less than 32kb. I tried with 12MB image and it worked fine :). Below is my code.
BufferedImage imBuff = ImageIO.read(inputStream);
BufferedImage resizedImg = resize(imBuff, 275, 75);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(resizedImg, "jpg", os);
encodedImage = new String(Base64.encode(os.toByteArray()));
private BufferedImage resize(BufferedImage image, int newWidth, int newHeight) {
int currentWidth = image.getWidth();
int currentHeight = image.getHeight();
BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
Graphics2D graphics2d = newImage.createGraphics();
graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.drawImage(image, 0, 0, newWidth, newHeight, 0, 0,
currentWidth, currentHeight, null);
graphics2d.dispose();
return newImage;
}
Hope this will help others who are trying to display a big image in small size in the web page.

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

How can I pass a captured image to a canvas?

I have a class that uses the devices camera to capture an image. My aim is to pass the captured image to a canvas on another layout.
This layout will then be saved along with a note entered into a textbox.I have figured out how to save the note and title and allow it to be opened but I'm not sure how I would go about passing the captured image to the layout and saving it along with the note.
Does anyone have any advice or pointers as to how I would go about this?
At the moment this is how I'm attempting to read the image file back to the layout after it is saved,but I'm not sure how to read a file into the canvas so obviously this solution isn't working yet:
if (NavigationContext.QueryString.ContainsKey("note"))
{
string s2 = ".jpg";
string filename = this.NavigationContext.QueryString["note"];
if (!string.IsNullOrEmpty(filename)) {
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile .GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
/*
if(filename.Contains(s2))
{
StreamReader reader = new StreamReader(stream);
this.capturedNoteCanvas = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
else
*/
{
StreamReader reader = new StreamReader(stream);
this.noteDataTb.Text = reader.ReadToEnd();
this.noteNameTb.Text = filename; reader.Close();
}
}
}
What I'm thinking is something like this:
Working wit CameraCaptureTask and Bitmaps
//Taking a writableBitmap object from cameracapturetask
void cameracapturetask_Completed(object sender, PhotoResult e)
{
try
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
WritableBitmap wb=new WritableBitmap (bmp.PixelWidth,bmp.PixelHeight);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
saving wb in storage
using (MemoryStream stream = new MemoryStream())
{
wb.SaveJpeg(stream, (int)bmp.PixelWidth, (int)bmp.PixelHeight, 0, 100);
using (IsolatedStorageFileStream local = new IsolatedStorageFileStream(App.PageName, FileMode.Create, mystorage))
{
local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
}
}
//Taking a WritableBitmap from canvas
If your canvas is containing the image, and also the canvas it attributed with some height and width properties then
WritableBitmap wb= new WritableBitmap(canvascontrol,null);
takes the canvas and saves it inside a writablebitmap object which can then be used for further image manipulations.

Retrieve image from my sql in GWT

I am working on GWT RPC. I am facing a problem in retrieving image from my SQL.
Here is my code:
Base64 bas = new Base64();
// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
UploadfileJpaController up = new UploadfileJpaController();
// this function returns the value in blob field in the form of byte array
byte[] b = up.findUploadfile(n);
String base64Contents = enc.encode(b).replaceAll("\\s+", "");
//String base64 = Base64Utils.toBase64(b);
base64Contents = "data:image/gif;base64,"+base64Contents;
return base64Contents;
But this is not working.. the image is not displayed. Please help :(
You should let a regular servlet take care of returning the image data, and not use GWT-RPC. The servlet should set the proper image/gif header and write the binary data to the response outputstream.
EDIT
This should look somewhat like this
public class FileDownloadServlet extends HttpServletv {
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Set content type
resp.setContentType("image/gif");
//Up to you!
byte[] binaryData = getDataFromDbase();
ByteArrayInputStream bis = new ByteArrayInputStream(binaryData);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = bis.read(buf)) >= 0) {
out.write(buf, 0, count);
}
bis.close();
out.close();
}
}
You url is going to be something like
http://server/application/image_servlet?id=123545 where you use the id parameter in the servlet to look up the image. And of course add the servlet to you web.xml. Good luck.

Resources