java - 缩放在 Java 中存储为 byte[] 的图像

标签 java image image-scaling

我上传了一个带有 struts 表单的文件。我将图像作为 byte[],我想对其进行缩放。

FormFile file = (FormFile) dynaform.get("file");
byte[] fileData = file.getFileData(); 
fileData = scale(fileData,200,200);

public byte[] scale(byte[] fileData, int width, int height) {
// TODO 
}

有人知道一个简单的函数可以做到这一点吗?

public byte[] scale(byte[] fileData, int width, int height) {
        ByteArrayInputStream in = new ByteArrayInputStream(fileData);
        try {
            BufferedImage img = ImageIO.read(in);
            if(height == 0) {
                height = (width * img.getHeight())/ img.getWidth(); 
            }
            if(width == 0) {
                width = (height * img.getWidth())/ img.getHeight();
            }
            Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0,0,0), null);

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();

            ImageIO.write(imageBuff, "jpg", buffer);

            return buffer.toByteArray();
        } catch (IOException e) {
            throw new ApplicationException("IOException in scale");
        }
    }

如果您像我一样用完了 tomcat 中的 Java 堆空间,请增加 tomcat 使用的堆空间。如果你使用 Eclipse 的 tomcat 插件,下一步应该适用:

In Eclipse, choose Window > Preferences > Tomcat > JVM Settings

Add the following to the JVM Parameters section

-Xms256m -Xmx512m

最佳答案

取决于数据格式。

但是,如果您使用的是 JPEG、GIF、PNG 或 BMP 之类的格式,则可以使用 ImageIO类。

类似于:

public byte[] scale(byte[] fileData, int width, int height) {
    ByteArrayInputStream in = new ByteArrayInputStream(fileData);
    try {
        BufferedImage img = ImageIO.read(in);
        if(height == 0) {
            height = (width * img.getHeight())/ img.getWidth(); 
        }
        if(width == 0) {
            width = (height * img.getWidth())/ img.getHeight();
        }
        Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0,0,0), null);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        ImageIO.write(imageBuff, "jpg", buffer);

        return buffer.toByteArray();
    } catch (IOException e) {
        throw new ApplicationException("IOException in scale");
    }
}

关于java - 缩放在 Java 中存储为 byte[] 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1228381/

相关文章:

python - 缩放图片的一部分

java - 在 EJB 中处理 TransactionTimeout 异常

java - 如何在 JavaFX 中重新着色图像

java - 在 android 中调整图片大小同时仍保持质量

android - 如何在android中将图像转换为字节数组并将字节数组转换为base64字符串?

javascript - react native : Image doesn't show in the view

php - 针对不同尺寸对齐/排序 HTML 中的图像

java - ORM 和 DAO 设计模式

java - 访问外部类这个实例

java - Tomcat/合流 : very long TLS handshake at start