I am retrieving a captcha image from the Java based package "SimpleCaptcha"
On the front end I just put the following in my page and I get a captcha image:
<img src="stickyImg" />
I want to reload this captcha image onclick using javascript.
I tried:
$("#theclickhandler").click(function(){
$("#stickyImg").load('stickyImg', function(response){
$("#stickyImg").attr('src', response);
});
return false;
});
This gets the image but outputs something like this (greatly shortened obviously):
<img src="captcha image�PNG �ݚ��L�23U�݆�}$�J����Dy����IEND�B`� ">
That looks like raw, binary data to me. How do I get this to work?
The src attribute of an image tag specifies to the browser where the image to load is, not the content of the image. So you're stuffing the content of the image into the place where you want the location to be, and that's giving you garbage because it simply doesn't make sense.
So, to reload the image, you need to tell the browser that the address of the image has changed. It's not sufficient to simply rewrite the location in the image's src attribute to the same address -- that won't tell the browser to change anything. You can overcome this by stuffing some random data in the query string, say, the time of the request. Like #mikerobi suggests, you can just rewrite the src tag, here with the modification of putting a timestamp in the query string (which your servlet will almost surely ignore):
$('#stickyImg').attr('src', 'stickyImg?' + (new Date().getTime()));
You can't use that approach to load images, you need to set the image url attribute to the path of the image generator.
$('#stickImg').attr('src', 'path/to/image/generator');
I don't know how many browsers support it, but it's possible to base64 encode an image, prefix it with (depending on the image format) "data:image/png; base64,", and use that as a URI for the image.
Related
I'm programming a desktop application using SWT and I use the browser in parts of the interface because of the flexibility.
I easily can introduce external images. An image in the file system:
<img src="/home/user/image.jpg" />
Or an image on the web:
<img src="http://some.cl/image.jpg" />
Can I obtain the images from a stream? In some place of my code I want to program something like this:
OutputSteam getExternaResource(String resourcePath)
I want to arbitrarily control the origin of the request.
I don't know of a direct way to do this, all I can think of is using javascript to set the image data as base64 string into the src of the image.
Using org.eclipse.swt.browser.Browser.execute(String) or maybe use org.eclipse.swt.browser.BrowserFunction.
The images should have an id which can be used in javascript:
<img id="image1" />
Edit: on the other hand, maybe it's easier to just parse the HTML previously and set the image base64 string there.
Depending on how you get the HTML you could do:
if you create the HTML yourself, just use <img src="data:image/png;base64.... convert the image to base64 and put it in the src attribute
if you read the HTML from an external source, you could use JSoup to parse the HTML and replace the image src attribute with a base64 string. afterwards use Browser.setText(String) to set the HTML of the browser, be aware that in that case relative paths (in links or images) don't work.
String html = "html";
Document doc = Jsoup.parse(html);
Elements img = doc.getElementsByTag("img");
for (Element element : img) {
String src = element.attr("src");
// READ image using the existing src, convert to base64 (using java.util.Base64)
String base64 = "";
element.attr("src", "data:image/png;base64,"+);
}
String newHtml = doc.html();
browser.setText(newHtml);
If you have control over the HTML page, i.e. it is generated by your code, possibly from a template, then you can embed the image.
The bytes of the image need to be base64 encoded and appended to the src attribute of the image tag like described here: http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/
i have a struts2 action which has a variable for an image which i want to display in a jsp page. when i display the value of the variable using the following:
<s:property value="variableName" />
i get the absolute path of the image file.
but when i try the following:
<img src='<s:property value="variableName" />' />
i get a blank there. i have even tried the following:
<img src="${variableName}" />
EDIT: i have done some thinking. the path of the image which is set is in temp folder of tomcat. is it because of that that i am unable to access it?
to no effect. what may be the issue in this?
Always keep in mind when doing web development what you have in server context and what travels to the client browser. If you do what you are suggesting, you will render and send to the client something like this:
<img src="c:\my_local_directory\some_image.jpg"></img>
Which means nothing to the client browser, which is surely executing in some other machine.
You should store your images somewhere where your application server can show them, and give always paths that are relative to your web application. For example, if you have stored some_image.jpg straight in your my-app.war file, something like:
<img src="/my-app/some_image.jpg"></img>
will always work. If you need to refine that image (imagine you need to put a watermark on it before) or need to recover its contents from somewhere (a BLOB in a database or something like that), you will need an entire new action in order to do it, for example:
<img src="/my-app/ImageAction.action?image=some_image"></img>
The src of the img tag must contain an absolute path, then only it can point to the image file from the client machine.
If the variableName contains an absolute path like this
http://localhost/images/pics/icon.gif
The img will finds the image from the server. Thus available always an hence you can use this.
<img src="${variableName}"/>
If the variableName is a relative path ie; something that's recognisable for the server.
/images/pics/icon.gif
The above path will be identified by the server but it wont be identified from the remote machine. In that case you need to have this
<img src="<c:url value=variableName/>" />
I have a desktop app that creates a graphics 2D object, sticks it in a panel and draws it. I am trying to convert this app to a webpage using servlets and jsps. I have been reading online for 2 days and can't wrap my head around how to do this, each example I find seems to leave out an important piece. I don't want to save the image to file because each user will get a new/different image.
Can I create the image in the servlet along with the other response variables and pass them to the jsp at the same time? Then call the image using something like ${response.image}.This seems be preferable but doesn't seem to work.
Or do I need a separate servlet just for the image (this seems harder)? Also how do I prepare the Graphics2D object to be used as an image in HTML?
You need to understand that it's the webbrowser who has got to download the invididual images based on the URLs of the <img> elements found in the retrieved HTML code and that it's not the webserver who has got to inline the image's raw content in the produced HTML code somehow.
You really need to create a standalone image servlet for this which listens on those specific URLs of the <img> elements. You can make the servlet reuseable by providing an unique image idenfitier in the request query string or request path info during generating the HTML code.
E.g.
<img src="imageServlet?param1=value1¶m2=value2" />
with a
#WebServlet("/imageServlet")
public class ImageServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create image based on request.getParameter() information.
// Set proper content type by response.setContentType().
// Write image to response.getOutputStream().
}
}
See also:
How to retrieve and display images from a database in a JSP page? - follows a similiar approach
I'll just answer on the first part of the question. To embed an image into an HTML page, you first need to generate the HTML page which will contain the following markup:
<img src="somePath" />
This HTML markup will be sent in the response to the request, and the browser will parse it. It will then send a second HTTP request to somePath, to download the bytes of the image.
So, you need to somehow store the generated image in memory and wait for the second request, and then send the bytes to the response, or you need to delay the image generation until the second request comes in. I much prefer the second solution. So the goal of the code handling the first request will just be to generate markup containing an img tag pointing to an appropriate URL. This URL should contain all the parameters necessary to actually generate the image.
For the second part, you will certainly have to create a BufferedImage instance, draw to its Graphics2D object, and use ImageIO to write this BufferedImage to the response output stream.
I would to get qr code from google chart API in my servlet (e.g. http://chart.apis.google.com/chart?chs=200x200&cht=qr&chld=M&chl=hello).
What libraries (jars) do i need and how should i save the response (maybe to byte array?)
What do you want to do with the image? If you want to just display it to the user, a simple <a href="..."> will suffice. if you want to do some processing (save it in a database, etc), open a connection (new URL("...").openStream()) and then either use ImageIO to get the image (as an image) or read the bytes.
If you're trying to just display the image to the user you don't need to do the HTTP GET request, just print the relevant HTML to the page and the client will do the request:
<img src="<your URL>" />
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 7 years ago.
I currently have to generate an image that displays the text of a string, i need to make this image on a Servlet and then somehow pass the image to a JSP page so that it can display it. I'm trying to avoid saving the image, and instead somehow stream the image to the JSP.
I haven't found a way of generating the image since i started with finding how to pass an image from the Servlet to the JSP adn got stuck.
EDIT:
The jsp page is already made and isn't created by the servlet, i have to pass the image into an already existing jsp
Any help is appreciated.
You need to write the image as a byte array to the response's output stream. Something like this:
byte[] imageBytes = getImageAsBytes();
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
Then in you JSP you just use a standard img element:
<img src="url to your servlet">
You can't1 return both in the same response, since you're returning different types (an HTML page of type text/html and an image of type image/jpeg, say).
For this sort of thing, I will generate the image during the initial servlet request (for the containing HTML page). I store it in a cache in my servlet, and write the HTML page with the image tag containing a URL to that image with the handle.
e.g. the browser asks for http://whatever/page
The servlet generates the image, and writes an HTML tag in the page like
<img src="http://whatever/image/unique_handle_to_image">
The browser will render the HTML page, and as part of that issue a new request to my servlet with the handle for the image.
e.g. the browser now asks for http://whatever/image/unique_handle_to_image
I then return the image as content type image/jpeg or similar.
So you have two requests going on. One for the page, in which you render the image and store it temporarily, and the second in which you return the image. You have to remember to clear the image cache, but that's all straightforward. I wouldn't worry about storing lots of images, since the two requests from the browser usually (!) come in quick succession.
I guess it's possible to use a data uri provided your browser supports it, and create something like
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
Note there are a number of caveats surrounding these. See the linked page.
I would do something along this lines to achieve this:
On the JSP page you put a link to an image:
<img src="servlet/path?word=value">the rest</img>
This link points to your servlet, it generates image using request parameters, you do not need to save it, just put it right into response's output stream. You have to remember to disable browser caching for this servlet.
JSP page is displayed first, next all the images are requested, it should work just fine.
Of course, you should not put the text to display in a parameter like this, you should propably encipher it somehow or store it in a HTTP session.
Hope this helps.
If I understand your problem correctly, the sequence of events will be:
You generate an HTML page;
That HTML page is sent to the client; and
The client's browser reads the image URL and requests it as a separate request.
So, you can't generate the image and pass it to the JSP. You can however generate a URL to get the image and put that in the JSP. That's easy enough to pass by the servlet putting it on the HttpServletRequest object (request scope in JSP). For example, generate:
<a href="http://myhost.com/image_servlet?id=1234"/>
You don't really say what that text is or what information is required to generate the image. If you can't encapsulate that in a GET URL, you may need to add extra information and put it in the HttpSession so it can be retrieved on the next get image request.
...
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length); // imageBytes - image in bytes
response.getOutputStream().write(imageBytes);//
outStream.flush();
outStream.close();