2

我正在构建一个小型图像缩放工具,用户首先将图像上传到网页,并在提交该表单时显示放大的图像以供保存。但是,当用户发送请求以使用不同的宽度和高度参数缩放同一图像时,就会出现问题。在这种情况下,我在 servlet 中设置的内容处置标头似乎不起作用,并且第二个请求后的图像仅使用 servlet 的类名而不是我在内容处置中提到的文件名和扩展名发送标题。

response.setContentType("image/jpeg");
response.setHeader("Content-disposition","inline;filename="+filename);

我也尝试在编写器本身中对其进行硬编码,但我使用的那个似乎没有任何文件名参数

private void doDownload(HttpServletResponse resp, BufferedImage bump,
            InputStream filecontent) throws IOException {

        //http://stackoverflow.com/questions/9340569/jpeg-image-with-wrong-colors
        OutputStream out = resp.getOutputStream();
        Iterator<ImageWriter> iter = ImageIO
                .getImageWritersByMIMEType("image/jpeg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(1);
        ImageOutputStream imgOut = new MemoryCacheImageOutputStream(out);
        writer.setOutput(imgOut);
        IIOImage image = new IIOImage(bump, null, null);
        writer.write(null, image, iwp);
        out.flush();
        out.close();
        writer.dispose();

    }

有什么方法可以在将图像写入输出流时设置图像的文件名?

4

1 回答 1

0

在这个类中声明一个静态整数变量。

private static int fileno=0;


private void doDownload(HttpServletResponse resp, BufferedImage bump,
            InputStream filecontent) throws IOException {

Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
String OUTPUTFILE = "C:/Users/Harish/Desktop/jpegFile"+fileno++;
File file = new File(OUTPUTFILE);
//Your fileName will be jpegFile0; and next time jpegFile1 and so on.
FileImageOutputStream imgOut = new FileImageOutputStream(file);
writer.setOutput(imgOut);
IIOImage image = new IIOImage(bump, null, null);
writer.write(null, image, iwp);
writer.dispose();

 }
于 2012-12-19T13:34:37.863 回答