【问题标题】:Cropping an uploaded image with Java使用 Java 裁剪上传的图像
【发布时间】:2013-04-01 16:59:42
【问题描述】:

我正在从 http 请求读取 servlet 中的图像文件。我想将其裁剪为正方形并将其写入文件。我可以使用以下代码实现这一点,但我使用临时文件首先写入原始图像。我怎么能不使用临时文件来做到这一点

                    File tempFile = new File(saveFileFrameTemp);
                    fileOut = new FileOutputStream(tempFile);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();

                    BufferedImage fullFrame = ImageIO.read(tempFile);
                    int height = fullFrame.getHeight();
                    int width = fullFrame.getWidth();
                    if (height > width)
                        ImageIO.write( fullFrame.getSubimage(0, (height-width)/2, width, width), "jpg", new File(saveFileFrame));
                    else
                        ImageIO.write( fullFrame.getSubimage((width-height)/2, 0, height, height), "jpg", new File(saveFileFrame));

                    tempFile.delete();

【问题讨论】:

    标签: java crop bufferedimage javax.imageio fileoutputstream


    【解决方案1】:

    如果不创建新的 BufferedImage 作为副作用,您将无法裁剪 BufferedImage

    【讨论】:

    • 没关系,我想要的只是不创建临时文件和额外的磁盘 io
    【解决方案2】:

    我使用 ByteArray 解决了它。

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(dataBytes, startPos, (endPos - startPos));
    
    BufferedImage fullFrame = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
    

    我在过程中使用了这个链接http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2015-08-10
      • 2014-01-12
      • 1970-01-01
      相关资源
      最近更新 更多