0

我想要做的是从磁盘获取图像文件,调整它的大小并使用 servlet 将其提供给客户端。

但是,我得到的是损坏的图像图标而不是调整大小的图像。我完全不知道可能出了什么问题。也许只有部分图像是流式传输的?这是我到目前为止的代码:

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortennobel.imagescaling.ResampleFilters;
import com.mortennobel.imagescaling.ResampleOp;

public class ImageServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String downloadPath = "/pathtofile";

        File file = new File(downloadPath);

        BufferedImage image = ImageIO.read(file);

        ResampleOp resampleOp = new ResampleOp(100, 100);
        resampleOp.setFilter(ResampleFilters.getLanczos3Filter());
        image = resampleOp.filter(image, null);

        WritableRaster raster = image.getRaster();
        DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
        byte[] imageBytes = data.getData();

        response.setContentType(FileBusiness.getFileMimeType(file));
        response.setContentLength(imageBytes.length);
        response.setHeader("Content-Disposition","inline; filename=\"" + file.getName() + "\"");

        byte[] buf = new byte[1024];
        int count = 0;
        try (InputStream in = new ByteArrayInputStream(imageBytes);
             OutputStream out = response.getOutputStream())
        {
            while ((count = in.read(buf)) >= 0)
            {
                out.write(buf, 0, count);
            }

            out.flush();
        }
    }
}

file是从磁盘读取的文件图像。

4

0 回答 0