导航:首页 > 文件处理 > java等比压缩图片

java等比压缩图片

发布时间:2023-03-18 20:03:10

java是怎么实现等比例缩小图片而不失真的啊

按照长宽的比例等比缩小,图片最好用矢量图片,不容易失真。。。

② java图片压缩比为1

java压缩图片,按照比例进行压缩

public static void main(String[] args) {
try {
//图片所在路径
BufferedImage templateImage = ImageIO.read(new File("C:\\Users\\晏丁丁\\Pictures\\图片1.png"));

//原始图片的长度和宽度
int height = templateImage.getHeight();
int width = templateImage.getWidth();

//通过比例压缩
float scale = 0.5f;

//通过固定长度压缩
/*int doWithHeight = 100;
int dowithWidth = 300;*/

//压缩段唯之后的轮陆长度和宽度
int doWithHeight = (int) (scale * height);
int dowithWidth = (int) (scale * width);

BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);

finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);

//图片输出路径,以及图握桐培片名
FileOutputStream fileOutputStream = new FileOutputStream("D:/image/tupian.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(finalImage);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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
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
文章知

③ java实现 图片等比缩放的原理

这在算缩放率啊.是用的这个吧?
getWidth(ImageObserver) - Method in class java.awt.Image
可能ImageObserver没有所以用Null
0.1好像是怕rate是0出问题,或是java的float运算要求的.
java的数值运算好像不是强项.

④ 求助java压缩图片存储大小的方法

可以使用Draw这个类,通过改变像素来改变存储大小,实例如下:

(StringsrcFilePath,StringdescFilePath)throwsIOException{
Filefile=null;
BufferedImagesrc=null;
FileOutputStreamout=null;
ImageWriterimgWrier;
ImageWriteParamimgWriteParams;

//指定写图片的方式为jpg
imgWrier=ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams=newjavax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
//要使用压缩,必须指定压缩方式为MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
//这里指定压缩的程度,参数qality是取值0~1范围内,
imgWriteParams.setCompressionQuality((float)1);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModelcolorModel=ImageIO.read(newFile(srcFilePath)).getColorModel();//ColorModel.getRGBdefault();
//指定压缩时使用的色彩模式
//imgWriteParams.setDestinationType(newjavax.imageio.ImageTypeSpecifier(
//colorModel,colorModel.createCompatibleSampleModel(16,16)));
imgWriteParams.setDestinationType(newjavax.imageio.ImageTypeSpecifier(
colorModel,colorModel.createCompatibleSampleModel(16,16)));

try{
if(isBlank(srcFilePath)){
returnfalse;
}else{
file=newFile(srcFilePath);System.out.println(file.length());
src=ImageIO.read(file);
out=newFileOutputStream(descFilePath);

imgWrier.reset();
//必须先指定out值,才能调用write方法,ImageOutputStream可以通过任何
//OutputStream构造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
//调用write方法,就可以向输入流写图片
imgWrier.write(null,newIIOImage(src,null,null),
imgWriteParams);
out.flush();
out.close();
}
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
returntrue;
}
publicstaticbooleanisBlank(Stringstring){
if(string==null||string.length()==0||string.trim().equals("")){
returntrue;
}
returnfalse;
}

⑤ Java怎么实现上传图片的等比缩放,原文件和缩放的文件都要上传到服务器

/**
*等比例缩放图片
*@paraminfile
*@paramoutfile
*@paramwidth
*@paramheight
*@paramquality
*@throwsIOException
*@throwsInterruptedException
*/
publicstaticvoidThumbnail(Stringinfile,Stringoutfile,intwidth,intheight,intquality)throwsIOException,InterruptedException{
//savethumbnailimagetoOUTFILE
//System.out.println("infile:"+infile);
BufferedImagethumbImage=null;
BufferedOutputStreamout=null;
Imageimage=null;
image=Toolkit.getDefaultToolkit().createImage(infile);
MediaTrackermediaTracker=newMediaTracker(newContainer());
mediaTracker.addImage(image,0);
mediaTracker.waitForID(0);
intthumbWidth=width;
intthumbHeight=height;
doublethumbRatio=(double)thumbWidth/(double)thumbHeight;
intimageWidth=image.getWidth(null);
intimageHeight=image.getHeight(null);
doubleimageRatio=(double)imageWidth/(double)imageHeight;
if(thumbRatio<imageRatio){
thumbHeight=(int)(thumbWidth/imageRatio);
}else{
thumbWidth=(int)(thumbHeight*imageRatio);
}
thumbImage=newBufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);
Graphics2Dgraphics2D=thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image,0,0,thumbWidth,thumbHeight,null);
out=newBufferedOutputStream(newFileOutputStream(outfile));
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam(thumbImage);
quality=Math.max(0,Math.min(quality,100));
param.setQuality((float)quality/100.0f,false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
thumbImage=null;
out=null;
image=null;
}


原文转载自:http://blog.chinaunix.net/uid-29337460-id-5035058.html

⑥ java如何实现把一个大图片压缩到指定大小的图片且长宽比不变

java要实现把一个大图片压缩到指定大小的图片且长宽比不变可以尝试以下操作:

⑦ java如何实现把一个大图片压缩到指定大小的图片且长宽比不变

java要实现把一个大图片压缩到指定大小的图片且长宽比不变可以尝试以下操作:

⑧ java压缩png图片

您转换的是图片的后缀名吧?您这样的方式已经把图片的信息删除了!
http://sjbbs.zol.com.cn/1/313_9068.html您去下载一个java图片压缩器吧
或者直接在Java下编辑代码来实习转换
package com.sun.util.cyw;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 图片工具类
* 压缩图片大小
* @author Cyw
* @version 1.0
*/
public class ZIPImage {

private File file = null;

private String outPutFilePath;

private String inPutFilePath;

private String inPutFileName;

private boolean autoBuildFileName;

private String outPutFileName;

private int outPutFileWidth = 100; // 默认输出图片宽

private int outPutFileHeight = 100; // 默认输出图片高

private static boolean isScaleZoom = true; // 是否按比例缩放

public ZIPImage() {
outPutFilePath = "";
inPutFilePath = "";
inPutFileName = "";
autoBuildFileName = true;
outPutFileName = "";
}

/**
*
* @param ipfp
* 源文件夹路径
* @param ipfn
* 源文件名
* @param opfp
* 目标文件路径
* @param opfn
* 目标文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = true;
outPutFileName = opfn;
}

/**
*
* @param ipfp
* 源文件夹路径
* @param ipfn
* 源文件名
* @param opfp
* 目标文件路径
* @param opfn
* 目标文件名
* @param aBFN
* 是否自动生成目标文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn,
boolean aBFN) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = aBFN;
outPutFileName = opfn;
}

public boolean isAutoBuildFileName() {
return autoBuildFileName;
}

public void setAutoBuildFileName(boolean autoBuildFileName) {
this.autoBuildFileName = autoBuildFileName;
}

public String getInPutFilePath() {
return inPutFilePath;
}

public void setInPutFilePath(String inPutFilePath) {
this.inPutFilePath = inPutFilePath;
}

public String getOutPutFileName() {
return outPutFileName;
}

public void setOutPutFileName(String outPutFileName) {
this.outPutFileName = outPutFileName;
}

public String getOutPutFilePath() {
return outPutFilePath;
}

public void setOutPutFilePath(String outPutFilePath) {
this.outPutFilePath = outPutFilePath;
}

public int getOutPutFileHeight() {
return outPutFileHeight;
}

public void setOutPutFileHeight(int outPutFileHeight) {
this.outPutFileHeight = outPutFileHeight;
}

public int getOutPutFileWidth() {
return outPutFileWidth;
}

public void setOutPutFileWidth(int outPutFileWidth) {
this.outPutFileWidth = outPutFileWidth;
}

public boolean isScaleZoom() {
return isScaleZoom;
}

public void setScaleZoom(boolean isScaleZoom) {
this.isScaleZoom = isScaleZoom;
}

public String getInPutFileName() {
return inPutFileName;
}

public void setInPutFileName(String inPutFileName) {
this.inPutFileName = inPutFileName;
}

/**
* 压缩图片大小
*
* @return boolean
*/
public boolean compressImage() {
boolean flag = false;

try {
if (inPutFilePath.trim().equals("")) {
throw new NullPointerException("源文件夹路径不存在。");
}
if (inPutFileName.trim().equals("")) {
throw new NullPointerException("图片文件路径不存在。");
}
if (outPutFilePath.trim().equals("")) {
throw new NullPointerException("目标文件夹路径地址为空。");
} else {
if (!ZIPImage.mddir(outPutFilePath)) {
throw new FileNotFoundException(outPutFilePath
+ " 文件夹创建失败!");
}
}

if (this.autoBuildFileName) { // 自动生成文件名
String tempFile[] = getFileNameAndExtName(inPutFileName);
outPutFileName = tempFile[0] + "_cyw." + tempFile[1];
compressPic();
} else {
if (outPutFileName.trim().equals("")) {
throw new NullPointerException("目标文件名为空。");
}
compressPic();
}

} catch (Exception e) {
flag = false;
e.printStackTrace();
return flag;
}

return flag;
}

// 图片处理
private void compressPic() throws Exception {
try {
// 获得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
throw new Exception("文件不可读!");
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (ZIPImage.isScaleZoom == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outPutFileWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outPutFileHeight + 0.1;

// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;

newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);

} else {
newWidth = outPutFileWidth; // 输出的图片宽度
newHeight = outPutFileHeight; // 输出的图片高度
}

BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);

/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);

FileOutputStream out = new FileOutputStream(outPutFilePath
+ outPutFileName);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();

}
} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* 创建文件夹目录
*
* @param filePath
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
private static boolean mddir(String filePath) throws Exception {
boolean flag = false;
File f = new File(filePath);
if (!f.exists()) {
flag = f.mkdirs();
} else {
flag = true;
}
return flag;
}

/**
* 获得文件名和扩展名
*
* @param fullFileName
* @return
* @throws Exception
*/
private String[] getFileNameAndExtName(String fullFileName)
throws Exception {
String[] fileNames = new String[2];
if (fullFileName.indexOf(".") == -1) {
throw new Exception("源文件名不正确!");
} else {
fileNames[0] = fullFileName.substring(0, fullFileName
.lastIndexOf("."));
fileNames[1] = fullFileName
.substring(fullFileName.lastIndexOf(".") + 1);
}
return fileNames;
}

public Image getSourceImage() throws IOException{
//获得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
return img;
}

/*
* 获得图片大小
* @path :图片路径
*/
public long getPicSize(String path) {
File file = new File(path);
return file.length();
}

}

//下面是测试程序

package com.sun.util.cyw;

import java.awt.Image;
import java.io.IOException;

public class ImageTest {
public static void main(String[] args) throws IOException {
ZIPImage zip=new ZIPImage("d:\\","1.jpg","d:\\test\\","处理后的图片.jpg",false);
zip.setOutPutFileWidth(1000);
zip.setOutPutFileHeight(1000);

Image image=zip.getSourceImage();
long size=zip.getPicSize("d:\\1.jpg");
System.out.println("处理前的图片大小 width:"+image.getWidth(null));
System.out.println("处理前的图片大小 height:"+image.getHeight(null));
System.out.println("处理前的图片容量:"+ size +" bit");

zip.compressImage();
}
}

⑨ java将图片按比例缩小

Image srcImg = ImageIO.read(new FileInputStream(fnSrc) );//取源图
int width = 600; //假设要缩小到600点像素
int height = srcImg.getHeight(null)*600/srcImg.getWidth(null);//按比例,将高度缩减

System.out.println("Width: "+srcImg.getWidth(null));// 这几行是调试用
System.out.println("Height: "+srcImg.getHeight(null));
System.out.println("Width2: "+width);
System.out.println("Height2: "+height);

Image smallImg =srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);//缩小

阅读全文

与java等比压缩图片相关的资料

热点内容
有个动漫女主蓝头发是程序员 浏览:998
云服务器资源评估 浏览:882
微云下载文件夹是空的 浏览:3
r9数控车的编程 浏览:403
为什么删不掉ksafe文件夹 浏览:291
理科男学编程用什么电脑 浏览:839
安阳弹性云服务器 浏览:570
压缩空气储罐有效期 浏览:408
英国文学PDF 浏览:175
软件编程需求 浏览:626
广州哪里解压 浏览:253
手机小视频怎么压缩 浏览:915
微信聊天界面源码 浏览:24
seo竞价推广点击价格算法公式 浏览:319
框架结构可以加密吗 浏览:218
python编译器怎么清除 浏览:73
linux全局socks代理 浏览:611
php微信抽奖 浏览:771
压缩算法嵌入式移植 浏览:531
php新手小例子 浏览:233