How to return an Image to browser in rest API in JAVA? - spring

I want to an image while I hit an API like localhost:8080:/getImage/app/path={imagePath}
While I hit this API it will return me an Image.
Is this possible?
Actually, I have tried this but it is giving me an ERROR.
Here is my code,
#GET
#Path("/app")
public BufferedImage getFullImage(#Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
return resizeImage(300, 300, objectKey);
}
public static BufferedImage resizeImage(int width, int height, String imagePath)
throws MalformedURLException, IOException {
BufferedImage bufferedImage = ImageIO.read(new URL(imagePath));
final Graphics2D graphics2D = bufferedImage.createGraphics();
graphics2D.setComposite(AlphaComposite.Src);
// below three lines are for RenderingHints for better image quality at cost of
// higher processing time
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(bufferedImage, 0, 0, width, height, null);
graphics2D.dispose();
System.out.println(bufferedImage.getWidth());
return bufferedImage;
}
My ERROR,
java.io.IOException: The image-based media type image/webp is not supported for writing
Is there any way to return an Image while hitting any URL in java?

You can use IOUtils. Here is code sample.
#RequestMapping(path = "/getImage/app/path/{filePath}", method = RequestMethod.GET)
public void getImage(HttpServletResponse response, #PathVariable String filePath) throws IOException {
File file = new File(filePath);
if(file.exists()) {
String contentType = "application/octet-stream";
response.setContentType(contentType);
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
// copy from in to out
IOUtils.copy(in, out);
out.close();
in.close();
}else {
throw new FileNotFoundException();
}
}

i didn't test it due to i don't have the environment in this machine, but logically it should work like the following, read it as input stream and let your method returns #ResponseBody byte[]
#GET
#Path("/app")
public #ResponseBody byte[] getFullImage(#Context UriInfo info) throws MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return IOUtils.toByteArray(is);
}
UPDATE
depending on #Habooltak Ana suggestion there is no need to create an input stream, the code should be look like the following
#GET
#Path("/app")
public #ResponseBody byte[] getFullImage(#Context UriInfo info) throws
MalformedURLException, IOException {
String objectKey = info.getQueryParameters().getFirst("path");
BufferedImage image = resizeImage(300, 300, objectKey);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
return os.toByteArray();
}

Just return a file object with correct HTTP-Headers (Content-Type and Content-Disposition) will work in most cases/environments.
Pseudocode
File result = createSomeJPEG();
/*
e.g.
RenderedImage rendImage = bufferedImage;
File file = new File("filename.jpg");
ImageIO.write(rendImage, "jpg", file);
*/
response().setHeader("Content-Disposition", "attachment;filename=filename.jpg;");
response().setHeader("Content-Type", "image/jpeg");
return ok(result);
See also:
file downloading in restful web services
what's the correct way to send a file from REST web service to client?

Related

SpringBoot REST produces pdf

I want to generate a dynamic PDF from a SpringBoot REST endpoint. The below generates a file but not a PDF. Any pointers in how to get a PDF file by altering the below code. Thanks in advance.
#GetMapping(value = "/generatePDF", produces = "application/pdf")
#SneakyThrows
public ResponseEntity<InputStreamResource> generatePDF(HttpServletRequest httpRequest,
HttpServletResponse response) {
String str = "Some test data goes here...";
byte[] pdf = str.getBytes();
File file = new File("C:\\test\\test.pdf");
FileUtils.writeByteArrayToFile(file, pdf);
FileInputStream fileInputStream = new FileInputStream(file);
return ResponseEntity.ok().contentLength(file.length())
.contentType(MediaType.APPLICATION_PDF)
.header("content-disposition", "filename=report.pdf")
.body(new InputStreamResource(fileInputStream));
try this
#GetMapping(value = "/generatePDF", produces = "application/pdf")
#SneakyThrows
public ResponseEntity<byte[]> generatePDF(HttpServletRequest httpRequest, HttpServletResponse response) {
String str = "Some test data goes here...";
byte[] pdf = str.getBytes();
File file = new File("C:\\test\\test.pdf");
FileUtils.writeByteArrayToFile(file, pdf);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
header.setContentLength(pdf.length);
header.set("Content-Disposition", "attachment; filename=" + "pdf-" + id + ".pdf");
return new ResponseEntity<>(pdf, header, HttpStatus.OK);
}

GridFSDBFile cannot be cast to org.springframework.web.multipart.MultipartFile

I'm coding a spring mvc webapp that uses images of type MultipartFile which i convert to byte[] and then to Inputstream and store it in MongoDB using GridFsTemplate.
Now the problem is I want to display the stored images in a webpage but whenever I try to, the database returns the image file as GridFSDBFiles and so tosses the following exception:
java.lang.ClassCastException: com.mongodb.gridfs.GridFSDBFile cannot be cast to org.springframework.web.multipart.MultipartFile
This is my DAO for storing images:
public void saveScan(Scan scan) throws IOException {
String owner = String.valueOf(scan.getPatientId());
String fileName = String.valueOf(scan.getPatientId() + "" + scan.getScanType());
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
String uploadTime = simpleDateFormat.format(date);
System.out.println("the scan type is " + scan.getScanType());
DBObject metaData = new BasicDBObject();
metaData.put("owner", owner);
metaData.put("fileName", fileName);
metaData.put("uploadTime", uploadTime);
byte[] scanBytes = scan.getScan().getBytes();
InputStream inputStream = new ByteArrayInputStream(scanBytes);
scanDaoImpl.SaveScan(inputStream, fileName, "image/jpeg", metaData);
}
And this is for retrieving the images:
public MultipartFile findOneScan(BigInteger patientId) {
MultipartFile multipartFile = (MultipartFile) gridFsTemplate
.findOne(new Query(Criteria.where("metadata.owner").is(patientId)));
return multipartFile;
And this is my controller for getting images
#ResponseBody
#RequestMapping(value = "/patients/{id}/scan", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> scanImage(#PathVariable("id") BigInteger id) throws IOException {
logger.debug("scanImage() is finding Image to display");
byte[] bs = patientScanServiceImpl.findOne(id).getBytes();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());
return new ResponseEntity<byte[]>(bs, httpHeaders, HttpStatus.OK);
}
This is my thymeleaf image tag:
<span>
<img th:src="#{/patients/{patientid}/scan(patientid=${patient.id})}" width="250" height="250"/>
</span>
Now I have more insight in this, and I have finally found a solution. You cannot directly cast a gridFSDBFile straight to byte[ ]; it must first be converted to OutputStream and then byte[ ] if it must be displayed. So I allowed my DAO method to return a GridFSDBFile but in the service layer I converted the GridFSDBFile to ByteArrayOutputStream and then to byte[ ].
Now my DAO method for retrieving images is
public GridFSDBFile findOneScan(BigInteger patientId, String scanType) {
String fileName = String.valueOf(patientId + "" + scanType);
GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(new Query(Criteria.where("metadata.fileName").is(fileName)));
return gridFSDBFile;
And my service layer which feeds the controller is
public byte[] findOne(BigInteger patientId, String scanType) throws IOException {
GridFSDBFile gridFSDBFile = scanRepository.findOneScan(patientId, scanType);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
gridFSDBFile.writeTo(outputStream);
byte[] bs = outputStream.toByteArray();
return bs;
}
And the whole thing works fine.

Should inputstream be closed explicitly when uploading file in jersey multipart?

I use Jersey multipart to upload file in controller
Here is the typical code case:
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have read many example code online, and the inputstream is not closed.
My question is that should I close the uploadedInputStream explicitly or manually? And why?

Spring MVC Thymeleaf: Displaying Buffered Image to HTML file

Can't display the image in the html file. Where did I go wrong?
#RequestMapping(value = "/image/{usr.id}", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
public #ResponseBody BufferedImage getImage(#PathVariable("usr.id") Long id) {
Attachment att = attSvc.getPicById(id);
try {
InputStream in = new ByteArrayInputStream(att.getAttachmentFile());
return ImageIO.read(in);
} catch (IOException e) {
System.out.println("ERROR:" + e);
throw new RuntimeException(e);
}
}
Please tell me if you need more references! Thank you so much.
This should solve your issue.
...
public #ResponseBody byte[] getImage(#PathVariable("usr.id") Long id) {
...
InputStream in = new ByteArrayInputStream(att.getAttachmentFile());
BufferedImage img = ImageIO.read(in);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", bao);
return bao.toByteArray();
...

Spring and serving files from outside of the web server

I want spring to serve certain files from the /tmp... directory, the specific directory isn't determined until shortly after the server starts so using <mvc:resources location="/images/**" mapping="/absolute/path/to/image/dir"/> won't seemingly work.
As Dave Newton noted - stream them from a controller. A very basic implementation:
#RequestMapping("/static/temp/{path}")
public void getResource(#PathVariable path, OutputStream os) {
//TODO proper IO management
InputStream is = new BufferedInputStream(new FileInputStream("/temp/" + path));
IOUtils.copy(is, os);
}
I do something like this:
#RequestMapping(value="/staticFile/{id}", method = RequestMethod.GET)
public void getPhotoRide2(HttpServletResponse response, #PathVariable int id) {
try {
FileInputStream in = new FileInputStream("your file");
OutputStream out = response.getOutputStream();
response.setContentType("your mime type");
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {}
}

Resources