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;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。