Ⅰ java实现图片预览功能,可以显示缩列图,具有上下页的功能求技术支持
把图片按照规定的比例压缩,然后保存至FTP,列表读取缩略图,单击显示原图。
/**
*压缩图片方法一(高质量)
*@paramoldFile将要压缩的图片
*@paramwidth压缩宽
*@paramheight压缩高
*@paramsmallIcon压缩图片后,添加的扩展名(在图片后缀名前添加)
*@paramquality压缩质量范围:<i>0.0-1.0</i>高质量:<i>0.75</i>中等质量:<i>0.5</i>低质量:<i>0.25</i>
*@parampercentage是否等比压缩若true宽高比率将将自动调整
*/
publicstaticvoidcompressImage(StringoldFile,intwidth,intheight,StringsmallIcon,
floatquality,booleanpercentage){
try{
Filefile=newFile(oldFile);
//验证文件是否存在
if(!file.exists())
thrownewFileNotFoundException("找不到原图片!");
//获取图片信息
BufferedImageimage=ImageIO.read(file);
intorginalWidth=image.getWidth();
intorginalHeight=image.getHeight();
//验证压缩图片信息
if(width<=0||height<=0||!Pattern.matches("^[1-9]\d*$",String.valueOf(width))
||!Pattern.matches("^[1-9]\d*$",String.valueOf(height)))
thrownewException("图片压缩后的高宽有误!");
//等比压缩
if(percentage){
doublerate1=((double)orginalWidth)/(double)width+0.1;
doublerate2=((double)orginalHeight)/(double)height+0.1;
doublerate=rate1>rate2?rate1:rate2;
width=(int)(((double)orginalWidth)/rate);
height=(int)(((double)orginalHeight)/rate);
}
//压缩后的文件名
StringfilePrex=oldFile.substring(0,oldFile.lastIndexOf('.'));
StringnewImage=filePrex+smallIcon+oldFile.substring(filePrex.length());
//压缩文件存放位置
FilesavedFile=newFile(newImage);
//创建一个新的文件
savedFile.createNewFile();
//创建原图像的缩放版本
Imageimage2=image.getScaledInstance(width,height,Image.SCALE_AREA_AVERAGING);
//创建数据缓冲区图像
BufferedImagebufImage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建一个Graphics2D
Graphics2Dg2=bufImage.createGraphics();
//重绘图像
g2.drawImage(image2,0,0,width,height,null);
g2.dispose();
//过滤像素矩阵
float[]kernelData={
-0.125f,-0.125f,-0.125f,
-0.125f,2,-0.125f,-0.125f,
-0.125f,-0.125f};
Kernelkernel=newKernel(3,3,kernelData);
//按核数学源图像边缘的像素复制为目标中相应的像素输出像素
ConvolveOpcOp=newConvolveOp(kernel,ConvolveOp.EDGE_NO_OP,null);
//转换像素
bufImage=cOp.filter(bufImage,null);
FileOutputStreamout=newFileOutputStream(savedFile);
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam(bufImage);
//设置压缩质量
param.setQuality(quality,true);
encoder.encode(bufImage,param);
out.close();
System.out.println(newImage);
}catch(Exceptione){
e.printStackTrace();
System.out.println("压缩失败!"+e.getMessage());
}
}
Ⅱ 求助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上传图片 生成缩略图,如果上传的图片尺寸比较小就压缩处理
//将图按比例缩小。
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
//则将下面的if else语句注释即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
throws Exception {
BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}
// System.out.println(ex);
File saveFile=new File(saveToFileStr);
File fromFile=new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, imgType, saveFile);
}
public static void main (String argv[]) {
try{
//参数1(from),参数2(to),参数3(宽),参数4(高)
saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",
"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",
120,120);
} catch(Exception e){
e.printStackTrace();
}
}
Ⅳ java如何实现压缩图片且保留图片原文件属性,比如拍摄日期
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;public class Zip {
// 压缩
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, null);
System.out.println("zip done");
out.close();
} private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
System.out.println("zipping " + f.getAbsolutePath());
if (f != null && f.isDirectory()) {
File[] fc = f.listFiles();
if (base != null)
out.putNextEntry(new ZipEntry(base + "/"));
base = base == null ? "" : base + "/";
for (int i = 0; i < fc.length; i++) {
zip(out, fc[i], base + fc[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}
} // 解压
public static void unzip(String zipFileName, String outputDirectory)
throws Exception {
ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry z;
while ((z = in.getNextEntry()) != null) {
String name = z.getName();
if (z.isDirectory()) {
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
System.out.println("MD " + outputDirectory + File.separator
+ name);
} else {
System.out.println("unziping " + z.getName());
File f = new File(outputDirectory + File.separator + name);
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
out.close();
}
}
in.close();
} public void deleteFolder(File dir) {
File filelist[] = dir.listFiles();
int listlen = filelist.length;
for (int i = 0; i < listlen; i++) {
if (filelist[i].isDirectory()) {
deleteFolder(filelist[i]);
} else {
filelist[i].delete();
}
}
dir.delete();// 删除当前目录
} public static void main(String[] args) {
try {
// TestZip t = new TestZip();
// t.zip("c:\\test.zip","c:\\test");
// t.unzip("c:\\test.zip","c:\\test2");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
Ⅳ JAVA如何优化处理图片,比如压缩质量
找段java输出JPEG图像的代码看看。
JPEGImageEncoder 做编码时候可以设定参数的。
JPEGEncodeParam.setQuality 即可变压缩比率
Ⅵ 求一个Java无损压缩图片的示例,把原图片复制到指定目录,按原图比例改变尺寸,不影响图片质量。
图片压缩就是讲图片的内存变小 对象数坑定有印象 你将压缩率改小一点 调整一下压缩率 到自己满意为止
Ⅶ 您好!请问用java怎么将截取png的图片中间一部分,以及如何压缩一个png图片
getSubimage方法是进行图片裁剪。
举例:
public static void main(String[] args) {
try {
//从特定文件载入
BufferedImage bi = ImageIO.read(new File("c:\test.png"));
bi.getSubimage(0, 0, 10, 10);//前两个值是坐标位置X、Y,后两个是长和宽
} catch (IOException e) {
e.printStackTrace();
}
}
以下是进行的图片压缩,涉及到多个工具类。
/**
* 图片工具类
* 压缩图片大小
* @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();
}
}