java图片缩小算法_图片缩小尺寸算法

package service;

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

//图片缩小尺寸算法

public class ReduceImgTest {

public static void main(String[] args) {

File srcfile = new File("C:/Users/85339/Desktop/wwwww/w.jpg");

File distfile = new File("C:/Users/85339/Desktop/wwwww/s3.png");

System.out.println("压缩前图片大小:" + srcfile.length());

//缩小到原来的0.2倍.,jpg格式的图片可以转换成png格式,直接更改存储图片文件名字就好了,好简单

//目标图片路径,处理好的图片存储路径,希望的图片宽,希望的图片高,缩放比例,如果缩放比例是0,则按照希望的宽高设置图片

reduceImg("C:/Users/85339/Desktop/wwwww/w3.jpg", "C:/Users/85339/Desktop/wwwww/s3.png", 0, 0, 0.2f);

System.out.println("压缩后图片大小:" + distfile.length());

}

//指定图片宽度和高度和压缩比例对图片进行压缩

//imgsrc 源图片地址

//imgdist 目标图片地址

//widthdist 压缩后图片的宽度

//heightdist 压缩后图片的高度

//rate 压缩的比例

public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist, Float rate) {

try {

File srcfile = new File(imgsrc);

// 检查图片文件是否存在

if (!srcfile.exists()) {

System.out.println("文件不存在");

}

// 如果比例不为空则说明是按比例压缩

if (rate != null && rate > 0) {

//获得源图片的宽高存入数组中

int[] results = getImgWidthHeight(srcfile);

if (results == null || results[0] == 0 || results[1] == 0) {

return;

} else {

//按比例缩放或扩大图片大小,将浮点型转为整型

widthdist = (int) (results[0] * rate);

heightdist = (int) (results[1] * rate);

}

}

// 开始读取文件并进行压缩

Image src = ImageIO.read(srcfile);

// 构造一个类型为预定义图像类型之一的 BufferedImage

BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

//绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像

//Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。

tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

String formatName = imgdist.substring(imgdist.lastIndexOf(".") + 1);

ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */, new File(imgdist) /* target */);

} catch (Exception ef) {

ef.printStackTrace();

}

}

//获取源图片的宽高大小

public static int[] getImgWidthHeight(File file) {

InputStream is = null;

BufferedImage src = null;

int result[] = {0, 0};

try {

// 获得文件输入流

is = new FileInputStream(file);

// 从流里将图片写入缓冲图片区

src = ImageIO.read(is);

result[0] = src.getWidth(null); // 得到源图片宽

result[1] = src.getHeight(null);// 得到源图片高

is.close(); //关闭输入流

} catch (Exception ef) {

ef.printStackTrace();

}

return result;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值