How to display an image in jsp? - java

I have a bytearray image.
I need to show that image in jpg format in jsp page and while clicking the image, i can download the image to my pc:
I am loading the image from my mysql db as byte array..
My code is
ResultSet res = statement.executeQuery("SELECT * FROM
upload_data where user_id = "+userID);
while (res.next()) {
contactDetails = new ContactDetails();
contactDetails.setContactPhoto(res.getBytes("photo"));
byteArrayBackToImage1(res.getBytes("photo"));
contactsList.add(contactDetails);
}
public void byteArrayBackToImage1(byte[] imageInByte){
try{
Random rand = new Random();
int numNoRange = rand.nextInt();
String number = String.valueOf(numNoRange);
//convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);
System.out.println("bImageFromConvert : "+bImageFromConvert);
/*ImageIO.write(bImageFromConvert, "jpg",
new File("c:\\"+number+".jpg")); */
}catch (Exception e) {
// TODO: handle exception
}
I need to show the image in jsp as
eg: image.jpg
image2.jpg
and by clicking image.jsp , i can download that image and save it to my pc
Please help

The HTML you generate in your JSP must contain an img element with an src pointing to the URL of a servlet or action which will load the image from the database and send it to the ouput stream with the image/jpeg content type.
// in your HTML :
<img src="/getImage.action?imageId=${id_of_the_image}"/>
// in the servlet mapped to /getImage.action:
// get the ID of the image from the request parameters
String imageId = request.getParameter("imageId");
byte[] imageData = getImageFromDatabase(imageId);
response.setContentType("image/jpeg");
response.getOutputStream().write(imageData);
All the browsers have a right-click - Save image as... menu item, so I wouldn't implement this in the app.

JSP:
<div id="profileDiv" style="padding: 10px; border: solid 2px #D6D6D6;">
<img src="imageDisplayProcess.do?pKey=<c:out value="${staff.staffId}" />"
width="117" height="160"
onError="loadImage()" onAbort="loadImage()" />
</div>
Servlet //imageDisplayProcess
imgByt = imageClass.getPhotograph();//return blob...
response.setContentType("image/jpg");
response.getOutputStream().write(imgByt);
response.getOutputStream().flush();
response.getOutputStream().close();

Related

Java Base64 Encoded Image isn't showing in JSP

I am trying to retrieve a blob from my db, convert it into a byte[] and then a base64 string and then show this in my JSP. However I am getting nothing on my JSP, not even an error in my console.
Here is my code for getting blob etc.
Blob blob = post.getImage();
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
String img = new String(Base64.getEncoder().encode(blobAsBytes));
System.out.println(img);
model.addAttribute("img", img);
And this is how I'm attempting to show the image in the JSP
<img src="data:image/jpeg;base64,${img}" width="100" height="100"></img>
This is my page source:
<img src="data:image/jpeg;base64,c2hhbG9t" width="100" height="100"></img>
What am I doing wrong here, when I convert the same photo on the web it outputs a huge string rather than just c2hhbG9t. Is there anyway I can get this large string.
Many thanks.
Jim

My images return as blank in PDF document

In my app I upload images to my company server
These images are converted to a pdf document and uploaded
I am using the built in PDFdocument for this, now my problem is the pages are dynamic depending on the amount of images the user selects or takes with the camera, the images are put into an ARRAYLIST(String)
I then call the position of the photo and use canvas to paint it to the pdf
Now my problem is the pdf document generates with the appropriate page numbers IE. If the user selects 4 images it returns 4 pages BUT there are NO images
I found the problem My second for loop doesn't work correctly as it doesn't give out a number ad I want it to so basicly
Code For The PDF
PdfDocument document=new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo;
PdfDocument.Page page;
Canvas canvas;
int i;
Bitmap image;
**here I loop for page Creation**
for (i=0; i < list.size(); i++) {
pageInfo=new PdfDocument.PageInfo.Builder(3000, 6000, 1).create();
page=document.startPage(pageInfo);
Here I loop to change the position of the images in the array list
this on is not looping through the arraylist positions like it should
for(int t = 0; t< list.indexOf(0); t+=1){
canvas=page.getCanvas();
image=BitmapFactory.decodeFile(String.valueOf(list.get (t)));
image.setDensity(DENSITY_XHIGH);
canvas.drawBitmap(image, 1, 1, null);
canvas.setDensity(DENSITY_XHIGH);
}
document.finishPage(page);
}
String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file=new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
String timeStamp=(new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
String targetPdf=directory_path + timeStamp + ".pdf";
File filePath=new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
Toasty.info(this, "PDF Created", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toasty.error(this, "Error making PDF" + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
1.Use PrintAttributes.build() to set attributes of the pdf properly
and pass printattrs to printerpdfDocument(context,/*print attributes obj goes here */)
Create a Rect() object
Using rect() object create pageviews in forloop and add these pageview to document
User FileOutputStream(// your pdf file), pass this to document, then
fileOutPutstream = new FileOutputStream(pdffilename);
doucument.writeTo(fileOutPutstream);
doucument.close();
fileOutPutstream.close(); // close your stream
Above is rough implementation, this should give you a idea to proceed.

Send email image Bufferedimage/ImageIO

I am trying to convert base64 image to a file that can be seen on gmail/outlook. Currently when I send an email with an image to my existing gmail, the image disappears, I can see all the text except for the image. But I can view the image in my apple mail. I have done some researching, it says that gmail has blocked base64 images. So the only way I can do is to convert base64 images.
<img alt=3D"" src=3D"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANsA=AABpCAIAAAA848FpAAAF/0lEQVR4nO2c2ZXjOAxFnW5l4VCcWyeADGo+elqmiIXgI......=3D" /></div>
I modified my codes using buffered image/imageIO but it doesnt make a difference when I send the email. Is there anything wrong with this? Or is there any other ways to allow base64 images to be seen?
This is my codes for the image.
String _message = _n.getRichcontent();
String[] _s = _message.split(",");
String message = _s[1];
System.out.println(_s[1]);
// create a buffered image
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
try {
imageByte = decoder.decodeBuffer(message);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
System.out.println("Reading complete.");
bis.close();
// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);
System.out.println("Writing complete." + outputfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error: "+e);
}
This is the code for the image to appear in my email.
_msg = _msg + _message + "<BR><BR>";
This is to send the email.
sendMail(_sender, _receipients, _subject, _msg);
No, there is no direct method. But ...
Imagine a html-table having the width of the image and the height of the image and every cell has a different background color like this:
<td style=background:#ddde22 />
That is about 31 bytes for every pixel.
If you have a 64x64 image its 64*64*31 bytes = 127kb in real-color.
Can you live with it?
If so, this discussion may help.

How to crop and rotate an image in pdf file in Java?

In Java, I have to crop and rotate an image in scanned pdf file and create another pdf file with the result image
For example, I have the image1 and want get the image2 centered in the page as result
How can I proceed?
Thanks!
The pdf is a scanned file.
It contains for example a student card.
I have to rotate the stutend card scanned on the right way and centered it in the A4 page.
I try to get the image like this :
PDDocument docIn = null;
File inputPdfFile = new File("C:\\test.pdf");
File output = new File("C:\\testOutput.png");
try {
// Read the pdf into a BufferedImage
docIn = PDDocument.load(inputPdfFile);
List<PDPage> pages = docIn.getDocumentCatalog().getAllPages();
PDPage page = pages.get(0);
// get the image
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
Then, I use the javaxt librairies to trim the image
Image image = new Image(output);
image.trim();
image.saveAs("C:\\projetCrop\\trimImage.png");
Now, how to detect the rotation angle?

How to convert an <img... in html to byte [] in Java

I have opened a webpage in HtmlUnit headless browser. Now that webpage contains a image html tag as follows:
<img src="..." />
So I want that image only. But the problem is that the same src URL of the image shows diff. image each time. Means, if we refresh the img src URL, then it shows diff. image each time.
So how to get the image that is displayed on the html page.
When you get the HTMLPage, you have to get the image through one of its method. You can then get an HtmlImage, which can be saved as a file. You'll just have to analyse this file later.
This is the function to store your image with fully qualified I
protected String saveImage(String imageUrl) throws Exception {
InputStream inputStream;
OutputStream os;
ByteArrayOutputStream byteArrayOutputStream;
String destinationFile = "File path where you want ot store the image";
URL url = new URL(imageUrl);
inputStream = url.openStream();
byteArrayOutputStream = new ByteArrayOutputStream();
os = new FileOutputStream(destinationFile);
int read;
String barcode = null;
while ((read = inputStream.read()) != -1) {
os.write(read);
byteArrayOutputStream.write(read);
barcode = byteArrayOutputStream.toString();
}
inputStream.close();
os.close();
byteArrayOutputStream.close();
return barcode;
}

Categories