美文网首页
Java 相关图片操作

Java 相关图片操作

作者: sprainkle | 来源:发表于2020-08-27 12:15 被阅读0次

    BufferedImage 转换为 InputStream

    /**
     * BufferedImage 转换为 InputStream
     * 
     * @param image
     * @return
     * @throws IOException
     */
    public static InputStream toInputStream(BufferedImage image) throws IOException {
        final ByteArrayOutputStream output = new ByteArrayOutputStream() {
            @Override
            public synchronized byte[] toByteArray() {
                return this.buf;
            }
        };
        ImageIO.write(image, "png", output);
        return new ByteArrayInputStream(output.toByteArray(), 0, output.size());
    }
    

    修改图片宽高

    /**
     * 修改图片宽高
     *
     * @param img
     * @param nWidth
     * @return
     */
    private static BufferedImage resize(BufferedImage img, int nWidth) {
        // 图片的宽
        int width = img.getWidth();
        // 图片的高
        int height = img.getHeight();
    
        int newWidth = width;
        int newHeight = height;
        // 放大
        if (nWidth > width) {
            double s = (double) nWidth / width;
            newWidth = (int) (width * s);
            newHeight = (int) (height * s);
        }
        // 缩小
        if (nWidth < width) {
            double s = width / (double) nWidth;
            newWidth = (int) (width / s);
            newHeight = (int) (height / s);
        }
    
        BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
        Graphics garphics = image.createGraphics();
        garphics.drawImage(img, 0, 0, newWidth, newHeight, null);
    
        return image;
    }
    

    相关文章

      网友评论

          本文标题:Java 相关图片操作

          本文链接:https://www.haomeiwen.com/subject/omdcsktx.html