I want to resize the image by giving pixels explicitly from out side.Here I am able to compress the image by hard coding by specifying compression quality.
I need to resize by explicit height and width too
Here I compressed the image by using this code:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ImageServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File f = new File("D:\\Compress");
File f1 = new File("D:\\Original");
if (!f.exists()) {
f.mkdir();
}
if (!f1.exists()) {
f1.mkdir();
}
String p = req.getParameter("myfile");
String actualPath = "D:/Original/" + p;
/*
* System.out.println(p); File file = new File(p); String s=
* file.getCanonicalPath(); System.out.println(s);
*/
File imageFile = new File(actualPath);
File compressedImageFile = new File("D://Compress/compressed_" + p + ".jpg");
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.3f;
// create a BufferedImage as the result of decoding the supplied
// InputStream
//reads image
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator writers = (Iterator) ImageIO.getImageWritersByFormatName("jpg");
// checks the format
java.util.Iterator<ImageWriter> iterator = (java.util.Iterator<ImageWriter>) writers;
if (!iterator.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) ((java.util.Iterator<ImageWriter>) writers).next();
//sends to output stream
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// compress to a given quality
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// appends a complete image stream containing a single image and
// associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(image, null, null), param);
// close all streams
is.close();
os.close();
ios.close();
writer.dispose();
// redirect to success page
resp.sendRedirect("./Success.html");
}
}
So code this working fine but its only resizing (means converting 43kb image file to 23kb) the image size.
Here I want to change the hieght and width of image.
Thanks in advance.
Related
i want to compress a jpeg Image, running a java program from an pl/sql procedure within th oracle database.
I want to call the java class from pl/sql procedure with the blob (jpeg image), an the java program should return the compresses image in a blob.
I have found this code from https://examples.javacodegeeks.com/desktop-java/imageio/compress-a-jpeg-file/ an it works fine and the jpeg images are compressed. But this program used jpeg-Files in the file system, i need the original image and the compresse image as blob parameter
I have used this program and have modified it to do what I need it to do.
To test my program, I get a jpg image from my database as blob via odbc an then call compressJPEG (myBlobCopy) with the blob. To show what happend, i do some output in the classes. The size of the blob before an after calling the compressJPEG is the same.
Here the output:
126 23190 myimage.jpg Length of retrieved Blob: 4284416
Length of copy Blob: 4284416
Call compressJPEG (myBlobCopy)
now in compressJPEG
Back from compressJPEG: Length of retrieved Blob: 4284416
Here the class. It seems, that the compressed image (blob) is not returned. Please can you help me!!!!!!
import java.sql.*;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.sql.Blob;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
//import java.sql.SQLException;
class OracleConCompressBLOB{
public static void main(String args[]){
try{
//step1 load the driver class
Blob myBlob = null;
Blob myBlobCopy = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
String dbURL = "jdbc:oracle:thin:#(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxxx)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = xxxx) ) )";
String strUserID = "xxxx";
String strPassword = "xxxxx";
//step2 create the connection object
Connection con=DriverManager.getConnection(dbURL,strUserID,strPassword);
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
// fuer pbent ResultSet rs=stmt.executeQuery("select PRFO_ID, PRFO_PRAX_ID , PRFO_DATEINAME, PRFO_FOTO from T_PRAFOTO where PRFO_ID = 17");
ResultSet rs=stmt.executeQuery("select PRFO_ID, PRFO_PRAX_ID , PRFO_DATEINAME, PRFO_FOTO from T_PRAFOTO where PRFO_ID = 166 FOR UPDATE");
if (rs.next()) {
myBlob = rs.getBlob(4);
myBlobCopy = myBlob;
System.out.println(rs.getInt(1)+" "+rs.getInt(2)+" "+rs.getString(3)+" Length of retrieved Blob: " + myBlob.length());
System.out.println(" Length of copy Blob: " + myBlobCopy.length());
System.out.println("Call compressJPEG (myBlobCopy) ");
compressJPEG (myBlobCopy) ;
System.out.println("back from compressJPEG: Length of retrieved Blob: " + myBlobCopy.length());
}
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
public static void compressJPEG(Blob blob) throws IOException {
// File imageFile = new File("myimage.jpg");
// File compressedImageFile = new File("myimage_compressed.jpg");
// InputStream is = new FileInputStream(imageFile);
// OutputStream os = new FileOutputStream(compressed ImageFile);
System.out.println("now in compressJPEG");
BufferedImage bufferedImage = null;
OutputStream outputStream = null;
float quality = 0.5f;
try {
// create a BufferedImage as the result of decoding the supplied InputStream
// BufferedImage image = ImageIO.read(is);
bufferedImage = ImageIO.read(blob.getBinaryStream());
outputStream = blob.setBinaryStream(0);
// test
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// compress to a given quality
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// appends a complete image stream containing a single image and
//associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(bufferedImage, null, null), param);
// close all streams
// is.close();
// os.close();
// ios.close();
// writer.dispose();
outputStream.flush();
ios.close();
outputStream.close();
writer.dispose();
} catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch(IllegalArgumentException e) {
e.printStackTrace();
}
}
}
I´m looking for a Java PDF Merger solution where I can streaming the merged pdf while I getting (example from a REST API) the PDF pages parts from a REST api.
A pseudo code should be something like this:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws Exception {
sOut = res.getOutputStream();
MergeDocument merger = MergeDocument.merge(sOut);
for (int i = 0; i < 1000; i++) {
byte[] contentPDF = restClient.get("http://mywebsite.com/files/mypdf"+i+".pdf");
merger.append(contentPDF);
sOut.flush(); // sending merged PDF bytes now
}
sOut.close();
}
My point is to not wast heap memory with all PDFs in memory before start sending it to user. In other words, when I get a "contentBytes pdf" from rest I want to send it to the user as a streaming now.
Hope someone can help me :)
Using itextpdf
package com.example.demo.controller;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/pdf")
public class PdfMerger {
#GetMapping
public void merge(HttpServletResponse response) {
Document document = new Document(PageSize.LETTER);
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=\"merged.pdf\"");
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
PdfCopy copy = new PdfCopy(document, outputStream);
document.open();
for (InputStream file : getPdfs()) {
copy.addDocument(new PdfReader(file)); // writes directly to the output stream
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen()) {
document.close();
}
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private List<InputStream> getPdfs() {
List<InputStream> list = new ArrayList<>();
for (int i = 0; i < 10; i++){
list.add(PdfMerger.class.getResourceAsStream("/pdf/1.pdf"));
list.add(PdfMerger.class.getResourceAsStream("/pdf/2.pdf"));
}
return list;
}
}
I am trying to download a file from my web application in an ActionForward java class. I have looked at many examples to try different solutions but none have worked so far. My knowledge is limited and have spent a good amount of time to get this to work.
From my jsp page a link hits an action in my struts config which takes the thread to an ActionForward return type method on a java class.
I then take the passed in file name and grab it from an amazon s3 bucket. With the file downloaded from the s3 bucket I now have the file bytes[].
I need to then have the file download to the local machine as most files do (appearing in the downloads folder and the web showing the download at the bottom bar of the page)
After following some examples I kept getting this error
Servlet Exception - getOutputStream() has already been called for this
response
I got past the error by doing
response.getOutputStream().write
Instead of creating a new OutputStream like this
OutputStream out = response.getOutputStream();
Now it runs without errors but no file gets downloaded.
Here is the java file I am attempting to do this in.
As you can see in the file below is a commented out DownloadServlet class which I tried as another attempt. I did this because a lot of the examples have classes the extends HttpServlet which I made DownloadServlet extend but it made no difference.
package com.tc.fms.actions;
import com.sun.media.jai.util.PropertyUtil;
import com.tc.fw.User;
import org.apache.commons.beanutils.PropertyUtils;
import java.io.*;
import java.io.File;
import java.util.ArrayList;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tc.fw.actions.BaseAction;
import org.apache.struts.upload.FormFile;
import io.isfs.utils.ObjectUtils;
import com.tc.fw.*;
import com.tc.fms.*;
import com.tc.fms.service.*;
public class FileDownloadAction extends BaseAction {
private static ObjectUtils objectUtils = new ObjectUtils();
private final int ARBITARY_SIZE = 1048;
public ActionForward performWork(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("In File Download Action");
ActionMessages errors = new ActionMessages();
User user = (User)request.getSession().getAttribute(User.lookupKey);
String fileName = (String) PropertyUtils.getSimpleProperty(form, "fileName");
String outboundDir = (String) PropertyUtils.getSimpleProperty(form, "outboundDir");
System.out.println("File Dir: " + outboundDir + " File Name: " + fileName);
try{
try {
// Get file from amazon
byte[] fileBytes = objectUtils.getFileDavid(outboundDir, fileName);
if (fileBytes != null) {
java.io.File file = File.createTempFile(fileName.substring(0, fileName.lastIndexOf(".") - 1), fileName.substring(fileName.lastIndexOf(".")));
FileOutputStream fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(fileBytes);
try {
/* DownloadServlet downloadServlet = new DownloadServlet();
downloadServlet.doGet(request, response, file);*/
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=" + file.getName());
InputStream in = new FileInputStream(file);
/*OutputStream out = response.getOutputStream();*/
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
response.getOutputStream().write(buffer, 0, numBytesRead);
}
} catch (Exception e) {
System.out.println("OutputStream EROOR: " + e);
}
} else {
System.out.println("File Bytes Are Null");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.no.file.found"));
saveErrors(request, errors);
return mapping.findForward("failure");
// Failed
}
} catch (Exception eee){
System.out.println("Failed in AWS ERROR: " + eee);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
}catch (Exception ee){
System.out.println("Failed in global try");
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("fms.download.failed"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
return mapping.findForward("success");
}
}
So I'm currently programming a java ee Backend, where I can store pictures or videos and I want to somehow stream the video from the backend to a client(internet browser) with the help of html5 < video> tag.The video part is not working it's just giving me a blackscreen,when I play the video, but the audio is playing. Image part is working well.
import com.dispway.restserver.facade.PlaylistEntryFacade;
import com.dispway.restserver.smallModel.SmallPlaylistEntry;
import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
#WebServlet("entry")
public class PlaylistEntryServlet extends HttpServlet {
#EJB
PlaylistEntryFacade playlistEntryFacade;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//entry-id
String e_id = req.getParameter("e_id");
//entry-type
String type = req.getParameter("type");
SmallPlaylistEntry entry = playlistEntryFacade.findById(Integer.parseInt(e_id));
ServletContext context = getServletContext();
String mimeType;
ServletOutputStream outputStream;
switch (type) {
case "1":
System.out.println("image-type");
mimeType = context.getMimeType(entry.getFilename());
if (mimeType == null) {
mimeType = "image/png";
}
resp.setContentType(mimeType);
outputStream = resp.getOutputStream();
outputStream.write(entry.getFile());
outputStream.close();
break;
case "2":
// NOT WORKING, I only get BlackScreen
System.out.println("video-type");
System.out.println(entry.getFilename());
mimeType = context.getMimeType(entry.getFilename());
if (mimeType == null) {
System.out.println("mime is null");
mimeType = "video/mp4";
}
System.out.println("MimeType: " + mimeType);
resp.setContentType(mimeType);
resp.setContentLength(entry.getFile().length);
//getFile returns a byte[]
BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(entry.getFile()));
byte[] content = new byte[4096];
int bytesRead;
outputStream = resp.getOutputStream();
while ((bytesRead = bufferedInputStream.read(content)) != -1) {
outputStream.write(content, 0, bytesRead);
}
bufferedInputStream.close();
outputStream.close();
break;
}
}
}
Sorry the video has the wrong codec, So the html <video> wasn't showing the video.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to write an buffered image into a file that appends the next buffered image bytes.I have the following code for which some runtime exception is thrown. when i run this code i get the following exception. Why and what has to be changed?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class FileT
{
public static void main(String[] args)
{
try {
BufferedImage originalImage = ImageIO.read(new File("ani.jpg"));
int i=0,c=0;
// convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
byte[] copybuf = new byte[1024];
baos.close();
while(i<imageInByte.length)
{
copybuf[c]=imageInByte[i];
c++;
if(i%1023==0)
{
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(copybuf);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new FileOutputStream(new File("ani1.jpg"),true));
}
copybuf = new byte[1024];
i++;
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)
at javax.imageio.ImageIO.write(ImageIO.java:1578)
at FileT.main(FileT.java:45)
if(i%1023==0){
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(copybuf);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new FileOutputStream(new File("ani1.jpg"),true));
}
copybuf = new byte[1024];
i++;
In this code you might want to change new FileOutputStream(new File()) to be casted to ImageOutputStream
It is very hard to determine from your question what you need, but I think this will fix it. If it doesn't just leave a comment and Ill try to fix it