Java 相关图片操作
2020-08-27 本文已影响0人
sprainkle
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;
}