远程下载、图片压缩到指定大小、FTP的上传、文件的删除 /copy
package com.cmmb.mall.service;
?
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
?
import javax.imageio.ImageIO;
?
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Service;
?
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
?
/**
?* 图片处理,压缩图片到指定大小
?* 本java类能将jpg、bmp、png、gif图片文件,进行等比或非等比的大小转换。 具体使用方法
?* compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))?
?* @author XP
?*
?*/
@Service
public class ImageToolDiapose {
?
? ? private File file = null; // 文件对象 ? ?
?
? ? private String inputDir; // 输入图路径 ??
?
? ? private String outputDir; // 输出图路径 ??
?
? ? private String inputFileName; // 输入图文件名 ??
?
? ? private String outputFileName; // 输出图文件名 ??
?
? ? private int outputWidth = 100; // 默认输出图片宽 ??
?
? ? private int outputHeight = 100; // 默认输出图片高 ??
?
? ? private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放) ??
?
? ? public ImageToolDiapose() { // 初始化变量 ??
?
? ? ? ? inputDir = ""; ? ?
?
? ? ? ? outputDir = ""; ? ?
?
? ? ? ? inputFileName = ""; ? ?
?
? ? ? ? outputFileName = ""; ? ?
?
? ? ? ? outputWidth = 100; ? ?
?
? ? ? ? outputHeight = 100; ? ?
?
? ? } ? ?
?
? ? public void setInputDir(String inputDir) { ? ?
?
? ? ? ? this.inputDir = inputDir; ? ?
?
? ? } ? ?
?
? ? public void setOutputDir(String outputDir) { ? ?
?
? ? ? ? this.outputDir = outputDir; ? ?
?
? ? } ? ?
?
? ? public void setInputFileName(String inputFileName) { ? ?
?
? ? ? ? this.inputFileName = inputFileName; ??
?
? ? } ? ?
?
? ? public void setOutputFileName(String outputFileName) { ? ?
?
? ? ? ? this.outputFileName = outputFileName; ? ?
?
? ? } ? ?
?
? ? public void setOutputWidth(int outputWidth) { ??
?
? ? ? ? this.outputWidth = outputWidth; ? ?
?
? ? } ? ?
?
? ? public void setOutputHeight(int outputHeight) { ? ?
?
? ? ? ? this.outputHeight = outputHeight; ? ?
?
? ? } ? ?
?
? ? public void setWidthAndHeight(int width, int height) { ? ?
?
? ? ? ? this.outputWidth = width; ??
?
? ? ? ? this.outputHeight = height; ? ?
?
? ? } ? ?
?
?
?
? ? /* ??
?
? ? ?* 获得图片大小 ??
?
? ? ?* 传入参数 String path :图片路径 ??
?
? ? ?*/ ? ?
?
? ? public long getPicSize(String path) { ? ?
?
? ? ? ? file = new File(path); ? ?
?
? ? ? ? return file.length(); ? ?
?
? ? } ??
?
?
?
? ? // 图片处理 ? ?
?
? ? public String compressPic() { ? ?
?
? ? ? ? try { ? ?
?
? ? ? ? ? ? //获得源文件 ? ?
?
? ? ? ? ? ? file = new File(inputDir + inputFileName); ? ?
?
? ? ? ? ? ? if (!file.exists()) { ? ?
?
? ? ? ? ? ? ? ? return ""; ? ?
?
? ? ? ? ? ? } ? ?
?
? ? ? ? ? ? Image img = ImageIO.read(file); ? ?
?
? ? ? ? ? ? // 判断图片格式是否正确 ? ?
?
? ? ? ? ? ? if (img.getWidth(null) == -1) { ??
?
? ? ? ? ? ? ? ? System.out.println(" can't read,retry!" + "<BR>"); ? ?
?
? ? ? ? ? ? ? ? return "no"; ? ?
?
? ? ? ? ? ? } else { ? ?
?
? ? ? ? ? ? ? ? int newWidth; int newHeight; ? ?
?
? ? ? ? ? ? ? ? // 判断是否是等比缩放 ? ?
?
? ? ? ? ? ? ? ? if (this.proportion == true) { ? ?
?
? ? ? ? ? ? ? ? ? ? // 为等比缩放计算输出的图片宽度及高度 ? ?
?
? ? ? ? ? ? ? ? ? ? double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1; ? ?
?
? ? ? ? ? ? ? ? ? ? double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1; ? ?
?
? ? ? ? ? ? ? ? ? ? // 根据缩放比率大的进行缩放控制 ? ?
?
? ? ? ? ? ? ? ? ? ? double rate = rate1 > rate2 ? rate1 : rate2; ? ?
?
? ? ? ? ? ? ? ? ? ? newWidth = (int) (((double) img.getWidth(null)) / rate); ? ?
?
? ? ? ? ? ? ? ? ? ? newHeight = (int) (((double) img.getHeight(null)) / rate); ? ?
?
? ? ? ? ? ? ? ? } else { ? ?
?
? ? ? ? ? ? ? ? ? ? newWidth = outputWidth; // 输出的图片宽度 ? ?
?
? ? ? ? ? ? ? ? ? ? newHeight = outputHeight; // 输出的图片高度 ? ?
?
? ? ? ? ? ? ? ? } ? ?
?
? ? ? ? ? ? ? ?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(outputDir + outputFileName); ??
?
? ? ? ? ? ? ? ?// JPEGImageEncoder可适用于其他图片类型的转换 ? ?
?
? ? ? ? ? ? ? ?JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); ? ?
?
? ? ? ? ? ? ? ?encoder.encode(tag); ? ?
?
? ? ? ? ? ? ? ?out.close(); ? ?
?
? ? ? ? ? ? } ? ?
?
? ? ? ? } catch (IOException ex) { ? ?
?
? ? ? ? ? ? ex.printStackTrace(); ? ?
?
? ? ? ? } ? ?
?
? ? ? ? return "ok"; ? ?
?
? ?} ? ?
?
? ?public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) { ? ?
?
? ? ? ?// 输入图路径 ? ?
?
? ? ? ?this.inputDir = inputDir; ? ?
?
? ? ? ?// 输出图路径 ? ?
?
? ? ? ?this.outputDir = outputDir; ? ?
?
? ? ? ?// 输入图文件名 ? ?
?
? ? ? ?this.inputFileName = inputFileName; ? ?
?
? ? ? ?// 输出图文件名 ??
?
? ? ? ?this.outputFileName = outputFileName; ? ?
?
? ? ? ?return compressPic(); ? ?
?
? ?} ? ?
?
? ?public String ?compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) { ? ?
?
? ? ? ?// 输入图路径 ? ?
?
? ? ? ?this.inputDir = inputDir; ? ?
?
? ? ? ?// 输出图路径 ? ?
?
? ? ? ?this.outputDir = outputDir; ? ?
?
? ? ? ?// 输入图文件名 ? ?
?
? ? ? ?this.inputFileName = inputFileName; ? ?
?
? ? ? ?// 输出图文件名 ? ?
?
? ? ? ?this.outputFileName = outputFileName; ? ?
?
? ? ? ?// 设置图片长宽 ??
?
? ? ? ?setWidthAndHeight(width, height); ? ?
?
? ? ? ?// 是否是等比缩放 标记 ? ?
?
? ? ? ?this.proportion = gp; ? ?
?
? ? ? ?return compressPic(); ? ?
?
? ?} ? ?
?
?
? ?/**
* 复制文件,对文件重命名
*?
* @param srcFile ?原文件地址
* @param targetPath ?要复制的目的
* @param fileName ? ?要复制的文件名字
*/
public ?void copyFile(String srcFile, String targetPath, String fileName) {
File file = null;
FileInputStream fis = null;
FileOutputStream fos = null;
File error = new File(targetPath);
int i = 0;
try {
if(!error.exists()){
error.mkdirs();
}
file = new File(srcFile);
byte[] b = new byte[Integer.parseInt(file.length() + "")];
fis = new FileInputStream(file);
fos = new FileOutputStream(targetPath + "/" + fileName);
while ((i = fis.read(b)) != -1) {
fos.write(b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除文件信息
*?
* @param srcFile
*/
public void deleteFile(String srcFile) {
File file = new File(srcFile);
file.delete();
}
/**
* 处理压缩图片
* @param url 图片原地址
* @param downUrl 下载到本地图片地址
* @param productName 商品名称
* @param tempUrl存放图片临时文件地址
* @param picImageUrl 处理之后的图片地址
* @param pcModel ? 机型
* @return ?处理后的图片地址,用于FTP上传
*/
public ?String[] useImageDiapose(String url,String downUrl,String productName,String tempUrl,String picImageUrl,String pcModel){
String httpUrl[] = new String[2];
try {
ImageToolDiapose mypic = new ImageToolDiapose(); ?
/*File picFileL = ?new File(picImageUrl+"L/");
if(!picFileL.exists()){
picFileL.mkdir();
}
File picFileM = ?new File(picImageUrl+"M/");
if(!picFileM.exists()){
picFileM.mkdir();
}*/
String filePath = mypic.saveUrlAs(url, downUrl);
System.out.println(filePath);
File file = new File(filePath);
?
String[] imgList = file.list();
for (int i = 0; i < imgList.length; i++) {
//文件名
String fileName = productName;
fileName += imgList[i].substring(imgList[i].lastIndexOf("."));
//copy到指定临时路径,对文件重命名
mypic.copyFile(filePath+"/"+imgList[i], tempUrl, fileName);
if(pcModel.equals("240x320")){
//机型1
//中图
mypic.compressPic(tempUrl,picImageUrl+"240x320/M/", fileName,fileName,125, 125, false);
httpUrl[0] = picImageUrl+"240x320/M/"+fileName;
//大图
mypic.compressPic(tempUrl,picImageUrl+"240x320/L/", fileName,fileName,240, 240, false);
httpUrl[1] = picImageUrl+"240x320/L/"+fileName;
}
if(pcModel.equals("320x480")){
//机型2
//中图
mypic.compressPic(tempUrl,picImageUrl+"320x480/M/", fileName,fileName,195, 195, false);
httpUrl[0] = picImageUrl+"320x480/M/"+fileName;
//大图
mypic.compressPic(tempUrl,picImageUrl+"320x480/L/", fileName,fileName,320, 320, false);
httpUrl[1] = picImageUrl+"320x480/L/"+fileName;
}
if(pcModel.equals("480x800")){
//机型3
//中图
mypic.compressPic(tempUrl,picImageUrl+"480x800/M/", fileName,fileName,290, 290, false);
httpUrl[0] = picImageUrl+"480x800/M/"+fileName;
//大图
mypic.compressPic(tempUrl,picImageUrl+"480x800/L/", fileName,fileName,480, 480, false);
httpUrl[1] = picImageUrl+"480x800/L/"+fileName;
}
if(pcModel.equals("540x960")){
//机型4
//中图
mypic.compressPic(tempUrl,picImageUrl+"540x960/M/", fileName,fileName,330, 330, false);
httpUrl[0] = picImageUrl+"540x960/M/"+fileName;
//大图
mypic.compressPic(tempUrl,picImageUrl+"540x960/L/", fileName,fileName,540, 540, false);
httpUrl[1] = picImageUrl+"540x960/L/"+fileName;
}
if(pcModel.equals("640x960")){
//机型4
//中图
mypic.compressPic(tempUrl,picImageUrl+"640x960/M/", fileName,fileName,390, 390, false);
httpUrl[0] = picImageUrl+"640x960/M/"+fileName;
//大图
mypic.compressPic(tempUrl,picImageUrl+"640x960/L/", fileName,fileName,640, 640, false);
httpUrl[1] = picImageUrl+"640x960/L/"+fileName;
}
//删除文件
mypic.deleteFile(tempUrl+fileName);
mypic.deleteFile(filePath+"/"+imgList[i]);
//System.out.println("处理图片成功---------------");
}
} catch (Exception e) {
System.out.println("处理图片失败----------------");
e.printStackTrace();
}
return httpUrl;
}
/**
* FTP上传
* @param dir 资源目录
* @param ftpip ip地址
* @param port 端口号
* @param ftpuser 用户名
* @param ftppassword 密码
* @param path 要上传到的目录
* @return
*/
public ?boolean ftpUpload(String dir, String ftpip, int port,
String ftpuser, String ftppassword,String path) {
?
System.out.println("================FTPINFOMATION======================"
+ "dir-" + dir + "ftpip-" + ftpip + "port-" + port
+ "ftpuser-" + ftpuser + "ftppasswd-" + ftppassword);
FTPClient ftpClient = new FTPClient();
?
FileInputStream fis = null;
?
File srcdir = new File(dir);
?
boolean a = false;
?
String ftp_model = "1";
?
try {
System.out.println(dir + "===========dir===========");
//与FTP建立连接
ftpClient.connect(ftpip, port);
?
if (!"".equals(ftp_model) && ftp_model.equals("1")) {
// 新添加 ( 被动模式 ),程序默认为主动
ftpClient.enterLocalPassiveMode();
}
//设置登录名密码
ftpClient.login(ftpuser, ftppassword);
// 设置上传目录,(Ftp用的目录)
ftpClient.changeWorkingDirectory(path);
?
ftpClient.setBufferSize(1024);
?
ftpClient.setControlEncoding("GBK");
?
// 设置文件类型(二进制)
?
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
?
if (srcdir.isDirectory()) {// 如果是目录
?
File files[] = srcdir.listFiles();
?
for (int i = 0; i < files.length; i++) {
?
if (files[i].isFile()) {
?
fis = new FileInputStream(files[i]);
?
ftpClient.storeFile(files[i].getName(), fis);
}
}
?
} else if (srcdir.isFile()) {// 如果是文件
?
fis = new FileInputStream(srcdir);
?
System.out.println("==========storeName========="+srcdir.getName());
System.out.println("==========storeName========="+new String(srcdir.getName().getBytes("GBK"),"iso-8859-1"));
ftpClient.storeFile(new String(srcdir.getName().getBytes("GBK"),"iso-8859-1"), fis);
}
?
a = true;
?
} catch (IOException e) {
?
e.printStackTrace();
?
throw new RuntimeException("FTP客户端出错!", e);
?
} finally {
?
IOUtils.closeQuietly(fis);
?
try {
?
ftpClient.disconnect();
?
} catch (IOException e) {
?
e.printStackTrace();
?
throw new RuntimeException("关闭FTP连接发生异常!", e);
?
}
?
}
return a;
?
}
?/**
? ? ?* 下载远程文件
? ? ?* @param photoUrl 文件路径
? ? ?* @param localPath 下载到本地的路径
? ? ?* @return 是否成功
? ? ?*/
? ? public String saveUrlAs(String photoUrl, String localPath) {
? ? String filePath = null;
? ? ? ? try {
? ? ? ?
? ? ? ? File file = new File(localPath);
? ? ? ? if(!file.exists()){
? ? ? ? file.mkdir();
? ? ? ? }
? ? ? ? //临时文件名
? ? ? ? String dowmFileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
? ? ? ?
? ? ? ? String tempFileName = file+dowmFileName;
? ? ? ?
? ? ? ? filePath = file.toString();
? ? ? ?
? ? ? ? ? ? URL url = new URL(photoUrl);
? ? ? ? ? ? HttpURLConnection connection = (HttpURLConnection) url.openConnection();
? ? ? ? ? ? DataInputStream in = new DataInputStream(connection.getInputStream());
? ? ? ? ? ? DataOutputStream out = new DataOutputStream(new FileOutputStream(tempFileName));
?
? ? ? ? ? ? byte[] buffer = new byte[4096];
? ? ? ? ? ? int count = 0;
? ? ? ? ? ? while ((count = in.read(buffer)) > 0) {
? ? ? ? ? ? ? ? out.write(buffer, 0, count);
? ? ? ? ? ? }
? ? ? ? ? ? out.close();
? ? ? ? ? ? in.close();
? ? ? ? ? ? return filePath;
?
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? System.out.println(e);
? ? ? ? ? ? return null;
? ? ? ? }
? ? }
?
? ? /**
? ? ?* 获取远程文件的内容(兼容HTTP与FTP)
? ? ?* @param urlString 文件路径
? ? ?* @return 文件内容
? ? ?*/
? ? public ?String getDocumentAt(String urlString) {
? ? ? ? StringBuffer document = new StringBuffer();
?
? ? ? ? try {
? ? ? ? ? ? URL url = new URL(urlString);
? ? ? ? ? ? URLConnection conn = url.openConnection();
? ? ? ? ? ? BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
? ? ? ? ? ? String line = null;
? ? ? ? ? ? while ((line = reader.readLine()) != null) {
? ? ? ? ? ? ? ? document.append(line + "\n");
? ? ? ? ? ? }
? ? ? ? ? ? reader.close();
? ? ? ? } catch (MalformedURLException e) {
? ? ? ? ? ? System.out.println("Unable to connect to URL: " + urlString);
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? System.out.println("IOException when connecting to URL: " + urlString);
? ? ? ? }
? ? ? ? return document.toString();
? ? }
? ?// main测试 ? ?
?
? ?// compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true)) ??
?
? ?public static void main(String[] arg) { ? ? ??
? ImageToolDiapose imageTool = new ImageToolDiapose();
??
? Properties props = new Properties();?
? //读取配置文件
? String urlpath = ImageToolDiapose.class.getClassLoader().getResource(("util.properties")).toString().substring(6);
? String empUrl = urlpath.replace("%20", " ");
? InputStream in = null;
? try {
? ?in = new BufferedInputStream(new FileInputStream(empUrl));
? ?props.load(in);
? } catch (FileNotFoundException e1) {
? ?e1.printStackTrace();
? } catch (IOException e1) {
? ?e1.printStackTrace();
? }
??
? System.out.println(props.get("ftpIp")+"="+props.getProperty("ftpPwd"));
?/* Properties p = new Properties();
try {
InputStream inStream = new FileInputStream(new File("/util.properties"));?
?
p.load(inStream);
} catch (Exception e) {
e.printStackTrace();
}
System.err.println(p.get("ftpUser"));*/
String url1[] = imageTool.useImageDiapose("http://img02.taobaocdn.com/bao/uploaded/i2/T1ZH6kXdtXXXacfj.9_103917.jpg","d:/img","806","c:/img/", "e:/image/","320x480");
imageTool.ftpUpload(url1[0], "192.168.1.117", 21,"pic", "123456","/320X480/M");
imageTool.ftpUpload(url1[1], "192.168.1.117", 21,"pic", "123456","/320X480/L");
?
//String url2[] = imageTool.useImageDiapose("http://img02.taobaocdn.com/bao/uploaded/i2/T16cfiXixbXXXPghU6_061818.jpg","d:/img","中华人民","c:/img/", "e:/image/","640x960");
//imageTool.ftpUpload(url2[0], "192.168.1.117", 21,"pic", "123456","/640X960/M");
//imageTool.ftpUpload(url2[1], "192.168.1.117", 21,"pic", "123456","/640X960/L");
? /*String photoUrl = "http://img01.taobaocdn.com/bao/uploaded/i1/T1UltYXhVbXXbIbiAZ_032637.jpg";
? ? ? ?String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
? ? ? ?System.out.println(fileName);
? ? ? ?String filePath = "D:/img";*/
? ? ? // System.out.println(ImageToolDiapose.getDocumentAt(photoUrl));
? ? ? ?//ImageToolDiapose.saveUrlAs(photoUrl, filePath + fileName);
// ? ? ? System.out.println("Run ok!\n Get URL file " + flag);
?
? ?} ? ?
?
}
--------------------------------------------------------------------------
本实例流程:1、下载远程文件图片到本地? 2、对图片处理(按照不同大小)? 3、将处理好的图片用FTP方式上传到指定目录