I am trying to retrieve images from database.
Currently i was able to show :
`com.mysql.jdbc.Blob#2aba2aba `
in my jsp output.
May i know how to convert that into an image?
i have use the below to call out the above
photo[i].getPhotoFileData();
This is more of an issue with the way HTML documents work than with your JSP. You need to understand that HTML doesn't embed images directly. Instead, it uses <img> tags to reference images hosted at different URLs.
In order to display an image stored in a database on an HTML page you're going to need a separate servlet that can handle requests for the image. Your JSP should render an HTML document like the following:
<html>
<head>
...
</head>
<body>
...
<img src="www.mydomain.com/images/1234.png" />
...
</body>
</html>
Then you would create a separate servlet to handle all the requests to /images which would make a database call and send the raw bytes from the blob it gets back to the response's output stream. Make sure you also set the Content-Type header correctly based on what image encoding you're using.
In order to send the image back to the requester you have one of two options. You can get the blob's bytes as an array and write that to the OutputStream (e.g. out.write(blob.getBytes(0,blob.length());). Or you can use the getBinaryStream() method and then copy bytes from the InputStream to the OutputStream. Here's an example of that:
public static void copy(Blob from, OutputStream to)
throws IOException {
byte[] buf = new byte[4096];
try(InputStream is = from.getBinaryStream()) {
while (true) {
int r = is.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
}
}
}
NB: This code has not been tested or even compiled, it should only be used as a starting point.
You're getting a Blob object - not it's contents. If you want to get raw byte data you have to ask the Blob object for it, e.g.:
Blob blob = photo[i].getPhotoFileData();
byte[] data = blob.getBytes(0, blob.length());
If you want to create an image on the fly, then just call:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
You can then save the image or ... actually I don't know what else. Thing. Stuff. Display it. Print. Limitless possibilities! Just like at zombo.com!
first convert blob to input stream to string . then use that String instead of image URL .
Converting blob to String
try {
Blob blob = staticOffer.getImage(); //blob of image from db
strOut = new StringBuffer();
String aux;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
while ((aux=br.readLine())!=null) {
strOut.append(aux);
}
offerPicStr = strOut.toString();
} catch (Exception e) {
e.printStackTrace();
}
Now use that string it html/jsp in following way
<img src="data:image/jpeg;base64,${offerPicStr}" width="100" height="100"></img>
Related
I want to display image on the page that is returned by the java controller.
Java controller:
public FileSystemResource RetrieveLogo(#PathVariable("UniqueCode") String Code){
// get image file
return fileSystemResource;
}
at java script controller, I make a service call to get the image .
Javascript controller:
$scope.logo = function() {
rest.retrieveLogoForMerchant({id: 'abcd'}).$promise.then(function(data) {
console.log("-------------success--------- " + angular.toJson(data));
$scope.logoImage = angular.toJson(data);
});
}
Here the console prints -
{"0":"�","1":"�","2":"�","3":"�","4":"\u00.......etc}
On Html page
<img ng-src="{{logoImage}}" height="100" width="100"/>
On the page image displays blank and gives error in the console that -
http://localhost:9090/%7B%220%22:%22%EF%BF%BD%22,%221%22:%22%EF%BF%BD%22,%2…22%EF%BF%BD%22,%22246%22:%22\u0007%22,%22247%22:%22\u0014%22,%22248%22:%22 400 (Bad Request)
Suggest me ,that how can I display image properly.
Thanks
Try removing the the angular.toJSON method here:
$scope.logoImage = angular.toJson(data);
And also
I think you are loading image through binary data append proper image encoding
to the data Eg: ng-source={{data:image/png;base64........}}
You need to set the right content type in response inside your Java controller, see below function
public void displayImage(HttpServletResponse response, byte[] imageArray) throws ServletException, IOException {
System.out.println("Inside display Image function");
if (imageArray != null && imageArray.length > 0) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
System.out.println("Image Array is not null :" + imageArray);
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
out.write(imageArray);
out.flush();
out.close();
} else {
System.out.println("Image is null");
}
}
Than you need to make sure append that appropriate header before data content while setting it to img tag.. #Naveen has already pointed about it in his answer. Basically you need to have something like this
<img src="data:image/png;base64,/*Your data part goes here*//>
You also need to encode the stream to Base64 before assigning it to img. I had below line in my jsp you can alter it to suit your need..
<img id="userProfileImg" height="150px" width="150px" name="userProfileImg" alt="../img/user_default_pic.png" src='data:image/jpg;base64,<%=Base64.encode(/*Blob data returned from database*/)%>'/>
Why don't you get the URL of the image via http (ajax call) and on success $scope.logoImage = data. data is the URL of the image retrieved via http.
I'm unable to save a Data URI in JSP. I am trying like this, is there any mistake in the following code?
<%# page import="java.awt.image.*,java.io.*,javax.imageio.*,sun.misc.*" %>
function save_photo()
{
Webcam.snap(function(data_uri)
{
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' + '<img src="'+data_uri+'"/>';
var dat = data_uri;
<%
String st = "document.writeln(dat)";
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(st);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
if (image != null)
ImageIO.write(image, "jpg", new File("d://1.jpg"));
out.println("value=" + st); // here it going to displaying base64 chars
System.out.println("value=" + st); //but here it is going to displaying document.writeln(dat)
%>
}
}
Finally, the image is not saved.
I think you didn't get the difference between JSP and JavaScript. While JSP is executed on the Server at the time your browser requires the web page, JavaScript is executed at the Client side, so in your browser, when you do an interaction that causes the JavaScript to run.
You Server (eg Apache Tomcat) will firstly execute your JSP code:
String st = "document.writeln(dat)";
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(st);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
if (image != null)
ImageIO.write(image, "jpg", new File("d://1.jpg"));
out.println("value=" + st);
System.out.println("value=" + st);
As you can see, nowhere is the value of st changed. Your broser will receive the following snippet from your server:
value=document.writeln(dat);
Since your browser is the one that executes JavaScript, he will execute it and show the Base64-encoded Image - but your server won't.
For the exact difference, read this article.
To make the code working, the easiest way is to redirect the page:
function(data_uri)
{
// redirect
document.location.href = 'saveImage.jsp?img='+data_uri;
}
Now, you can have a JSP-page called saveImage.jsp that saves the Image, and returns the webpage you had already, and write the dara_uri into the element results.
Another, but more difficult way is to use AJAX. Here is an introduction to it.
You are trying to use JavaScript variables in Java code. Java code is running on your server, while Javascript code runs in user's browser. By the time JavaScript code executes, your Java code has already been executed. Whatever you're trying to do, you have to do it in pure javascript, or send an AJAX call to your server when your Javascript code has done it's thing.
I am new to the blob data conversion of content. I am reading the emails and saving into database with body type as BLOB, if we have image embed into email even those are saving into it. but the problem is retrieving back and showing it to users. The image re-creation is not happening it says image path failed.
the src in image tag would be something like this.
cid:image001.png#01CF630F.005FA080
Please help with the suitable java code which 'll form image back and we can show into the division .
thanks in advance.
I have solved same problem, by making a sevlet that returns the byte[] of the image. And call this servlet within the img src tag.
Example :
This method will give you byte[] for any file, and method is in Utilities class
public static byte[] getFileData ( String fileName ){
File f = new File(fileName);
byte data [] = new byte[ (int) f.length() ];
try {
FileInputStream fis = new FileInputStream(f);
fis.read(data);
fis.close();
return data;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}**
and I have called this method from doGet of the servlet as following:
final String imageName = request.getParameter("imageName");
byte[] imageData = Utilities.getFileData( ROOT_DIR + imageName );
response.getOutputStream().write(imageData);
In above code ROOT_DIR is also defined as C:\Temp\FormData\Images\
My div is like this:
<div>
<img src='http://localhost:9080/LoadImage?imageName=one.png' />
</div>
I want to attach files to CouchbaseLite document. How can I do so? I did not find any code sample on official CBLite website for this - CBLite code Sample. I am still stuck how to accomplish it.
One way to do this in code is:
Document document = mDatabaseLocal.createDocument();
document.getCurrentRevision().createRevision().setAttachment(name, contentType, contentStream);
But this is not clear. *What should be the name?* - It is the absolute path of the attachment on your local disk?
For contentType: I do not know if there exists any enum class or constants that I can pass as contentType.
How would I attach multiple files to a document? Do I need to create unsavedRevision for every attachment?
The name must be unique per attachment, and doesn't refer to the local file, it refers to the name that you want to fetch it from on the document.
In this case you would call createRevision() once and then setAttachment() multiple times on the revision, before saving it.
you have to put an inputstream as attachment to your document.
A example can be found here CouchBase Attachment Example.
You have to convert each file into an InputStream and then you can set it to the document.
For convert you can use something like this:
private InputStream getAsStream(YourData data)
{
baos = new ByteArrayOutputStream();
try
{
objOstream = new ObjectOutputStream(baos);
objOstream.writeObject(data);
} catch (IOException e)
{
e.printStackTrace();
}
bArray = baos.toByteArray();
bais = new ByteArrayInputStream(bArray);
return bais;
}
In this example YourData can be every object or some of your own objectTypes.
Hope this explanation will help you.
I trying to upload a zip file. In my project i am using DWR in the client side and Java in server side. As i have seen in DWR tutorials for uploading data(Its not in their website. They are providing it with dwr.rar bundle) they getting input by the below lines.
var image = dwr.util.getValue('uploadImage');
var file = dwr.util.getValue('uploadFile');
var color = dwr.util.getValue('color');
dwr.util.getValue() is a utility to get the value of any element, in this case a file object.//Mentioned in the tutorial.
So, i get a zip file using that utility by the below code.
Javascript:
function uploadZip(){
var file = dwr.util.getValue("uploadFile");
dwr.util.setValue("uploadFile", null);
DataUpload.uploadData(file, function(data){
if(data != null){
$("#zipURL").html("<p>Upload Completed!!!</p>");
$("#zipURL").append("Location: "+data.path2);
}
});
}
HTML:
<html>
<head>ZIP Uploader
</head>
<body>
<table>
<tr><td>Select File: </td><td><input type="file" id="uploadFile" /></td>
<tr><td><input type="button" value="Upload" onclick="uploadZip()" /></td></tr> </table>
<div id="result"><span id="imgURL"></span>
<span id="zipURL"></span></div>
</body>
</html>
The Java Code is:
public class DataUpload {
private static String DATA_STORE_LOC = "D:/BeenodData/Trials/";
public Path uploadData(InputStream file) throws IOException{//In the tutorial the
//parameters are in type of BufferedImage & String.
//They used it for image and text file respectively.
//In an another example(out of DWR site) they used InputStream for receiving
//image
try {
byte[] buffer = new byte[1024];
int c;
File f2 = new File(DATA_STORE_LOC+dat+".zip");
path.setPath2(DATA_STORE_LOC+dat+".zip");
FileOutputStream fos = new FileOutputStream(f2);
c = file.read();
System.out.println(c);
while ((c = file.read()) != -1) {
fos.write(c);
}
file.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
This code runs without error. But the output is a Empty zip file. I know i doing something wrong. I unable to find that.
Actually, i am receiving a zip file as
InputStream.
How should i have to write a
InputStream(a zip file) to a zip.file
using java?
What will happen if i set the java
method parameter as ZipFile file? I
didnt tried it, yet because, i am
still searching a good tutorial to
learn about it.
Any Suggestion or Links would be more appreciative!!!!!
Thanks in Advance!!!
Here you have 2 examples about creating a ZIP file:
http://www.java2s.com/Tutorial/Java/0180_File/0601_ZipOutputStream.htm
Here is an example about reading a ZIP file:
http://www.kodejava.org/examples/334.html
I have also implemented the Same kind of backend Code in Java, and I was facing the same Issue of Zip file being made, but its content being empty.
Later I found that the Request I was making to API, in that the file I was Attaching was not in --data-binary format. So, I then made the request in this Format.
curl --data-binary #"/mnt/c/checknew.zip" http://localhost/api/upload
I am not sure what request format you are making either in multipart/form-data or Base-64 encoded.
My code worked when I made a Base-64 encoded Request (i.e --data-binary)