作者热门文章
- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章java实现图片压缩的思路与代码由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
本文实例为大家分享了java实现图片压缩的相关代码,供大家参考,具体内容如下 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import
java.awt.Image;
import
java.awt.image.BufferedImage;
import
java.io.ByteArrayOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
javax.imageio.ImageIO;
public
class
ImageProcess {
/**
* 图片
*/
private
Image img;
/**
* 宽度
*/
private
int
width;
/**
* 高度
*/
private
int
height;
/**
* 文件格式
*/
private
String imageFormat;
/**
* 构造函数
* @throws Exception
*/
public
ImageProcess(InputStream in,String fileName)
throws
Exception{
//构造Image对象
img = ImageIO.read(in);
//得到源图宽
width = img.getWidth(
null
);
//得到源图长
height = img.getHeight(
null
);
//文件格式
imageFormat = fileName.substring(fileName.lastIndexOf(
"."
)+
1
);
}
/**
* 按照宽度还是高度进行压缩
* @param w int 最大宽度
* @param h int 最大高度
*/
public
byte
[] resizeFix(
int
w,
int
h)
throws
IOException {
if
(width / height > w / h) {
return
resizeByWidth(w);
}
else
{
return
resizeByHeight(h);
}
}
/**
* 以宽度为基准,等比例放缩图片
* @param w int 新宽度
*/
public
byte
[] resizeByWidth(
int
w)
throws
IOException {
int
h = (
int
) (height * w / width);
return
resize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
* @param h int 新高度
*/
public
byte
[] resizeByHeight(
int
h)
throws
IOException {
int
w = (
int
) (width * h / height);
return
resize(w, h);
}
/**
* 强制压缩/放大图片到固定的大小
* @param w int 新宽度
* @param h int 新高度
*/
public
byte
[] resize(
int
w,
int
h)
throws
IOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image =
new
BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img,
0
,
0
, w, h,
null
);
// 绘制缩小后的图
ByteArrayOutputStream baos =
new
ByteArrayOutputStream();
ImageIO.write(image, imageFormat, baos);
return
baos.toByteArray();
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,轻松实现图片压缩操作.
最后此篇关于java实现图片压缩的思路与代码的文章就讲到这里了,如果你想了解更多关于java实现图片压缩的思路与代码的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我有以下场景:有 1 个包含书籍的表和两对包含销售订单和采购订单交易的表 (HD/IT),这些交易通过销售订单 ID 连接。表结构如下: CREATE TABLE `books` ( `id` i
我是一名优秀的程序员,十分优秀!