Java 相关图片操作

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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。