java处理图片
// 获取原始图片流 BufferedImage originalBI = ImageIO.read(new File("D://in.jpg")); // 获取原始图片宽高 int originalWidth = originalBI.getWidth(); int originalHeight = originalBI.getHeight(); // 设置缩放图片宽高 int scaledWidth = originalWidth * 2; int scaledHeigth = originalHeight * 2; // int scaledWidth = originalWidth / 2; // int scaledHeigth = originalHeight / 2; // 设置缩放图片流 BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeigth, BufferedImage.TYPE_INT_RGB); // 设置缩放图片画笔 Graphics2D g = scaledBI.createGraphics(); g.setComposite(AlphaComposite.Src); // 绘制缩放图片 g.drawImage(originalBI, 0, 0, scaledWidth, scaledHeigth, null); g.dispose(); // 输出缩放图片 ImageIO.write(scaledBI, "jpg", new FileOutputStream(new File("D://out.jpg")));
thumbnailator处理图片(压缩、裁切、旋转、添加水印)
/* * java工程图片压缩 添加thumbnailator-0.4.7.jar(Build Path --> Add to Build Path) * thumbnailator 是一个用来生成图像缩略图、裁切、旋转、添加水印等操作的 Java 类库 */ // 原图 String originalImage = "images/image.jpg"; /* * 指定大小(默认按比例)进行缩放 * size(width,height) * 若图片横比200小,高比300小,不变 * 若图片横比200小,高比300大,高缩小到300,图片比例不变 * 若图片横比200大,高比300小,横缩小到200,图片比例不变 * 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300 */ Thumbnails.of(originalImage).size(200, 300).toFile("images/image_200x300.jpg"); /* * 不按照比例,指定大小进行缩放 * keepAspectRatio(false) */ Thumbnails.of(originalImage).size(200, 300).keepAspectRatio(false).toFile("images/image_200x300_fixed.jpg"); /* * 按照比例进行缩放 * scale(比例) */ Thumbnails.of(originalImage).scale(0.5f).toFile("images/image_50%.jpg"); Thumbnails.of(originalImage).scale(1.5f).toFile("images/image_150%.jpg"); /* * 旋转 * rotate(角度),正数:顺时针 负数:逆时针 */ Thumbnails.of(originalImage).size(200, 300).rotate(90).toFile("images/image_200x300_+90.jpg"); Thumbnails.of(originalImage).scale(1.0f).rotate(-90).toFile("images/image_-90.jpg"); /* * 水印 * watermark(位置,水印图,透明度) * outputQuality(比例)合成图片按比例质量输出 */ BufferedImage waterImage = ImageIO.read(new File("images/watermark.jpg")); Thumbnails.of(originalImage).scale(1.0f).watermark(Positions.CENTER, waterImage, 0.5f).outputQuality(1.0f) .toFile("images/image_watermark_center.jpg"); /* * 裁剪 * sourceRegion(位置,长,宽) * sourceRegion(起始x坐标, 起始y坐标,长,宽) */ Thumbnails.of(originalImage).sourceRegion(Positions.TOP_LEFT, 400, 400).scale(1.0f) .toFile("images/image_region_top_left.jpg"); Thumbnails.of(originalImage).sourceRegion(0, 0, 400, 400).size(200, 300).keepAspectRatio(true) .toFile("images/image_region_0x0.jpg"); /* * 指定输出格式 * outputFormat(图像格式) */ Thumbnails.of(originalImage).size(200, 300).outputFormat("png").toFile("images/image_200x300.png"); /* * 输出到OutputStream * toOutputStream(流对象) */ OutputStream os = new FileOutputStream("images/image_200x300_OutputStream.png"); Thumbnails.of(originalImage).size(200, 300).toOutputStream(os); /* * 输出到BufferedImage * asBufferedImage() */ BufferedImage bf = Thumbnails.of(originalImage).size(200, 300).asBufferedImage(); ImageIO.write(bf, "jpg", new File("images/image_200x300_BufferedImage.jpg"));