Ⅰ 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();
}
}