读片处理工具类

package com.zhaopin.web.www.util;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.bj58.wf.mvc.client.RequestFile;
import com.bj58.wf.mvc.client.UploadRequest;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;

public class ImagesUtil {
    
    public static String post(String url,Map<String,String> data) throws IOException {
        URL postUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setReadTimeout(20000);
        connection.setConnectTimeout(10000);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        if(data!=null){
            StringBuilder builder = new StringBuilder();
            Iterator<Entry<String, String>> entrys = data.entrySet().iterator();
            while(entrys.hasNext()){
                Entry<String, String> entry = entrys.next();
                builder.append(entry.getKey());
                builder.append('=');
                builder.append(URLEncoder.encode(entry.getValue(), "utf-8"));
                builder.append('&');
            }
            if(builder.length()>0){
                builder.deleteCharAt(builder.length()-1);
            }
            out.writeBytes(builder.toString()); 
            out.flush();
            out.close(); 
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(),"UTF-8"));
        String lines="",line; 
        while ((line = reader.readLine()) != null) { 
            lines+=line;
        } 
        reader.close();
        connection.disconnect();
        return lines;
    }
    //图片压缩
    public static byte[] processUploadImage(byte imputImage[],int maxSize){
        try{
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imputImage);
            BufferedImage imgOreign = ImageIO.read(byteArrayInputStream);

            imputImage = null;
            
            int width = imgOreign.getWidth();
            int height = imgOreign.getHeight();
            if(width>maxSize||height>maxSize){
                if(imgOreign.getWidth()>imgOreign.getHeight()){
                    height = maxSize*height/width;
                    width = maxSize;
                }else{
                    width = maxSize*width/height;
                    height = maxSize;
                }
            }
            
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(imgOreign, 0,0, width, height, null);
            g.dispose();
            
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            JPEGImageWriter imageWriter  =  (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpg").next();
            ImageOutputStream ios  =  ImageIO.createImageOutputStream(outStream);
            imageWriter.setOutput(ios);

            IIOMetadata imageMetaData  =  imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), null);
            
            JPEGImageWriteParam jpegParams  =  (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
            jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(0.8f);
            
            imageWriter.write(imageMetaData, new IIOImage(image, null, null), null);
            ios.close();
            imageWriter.dispose();

            return outStream.toByteArray();
        }catch(Exception e){
            return new byte[0];
        }
    }
    
    public static String downloadImage(String uri,ByteArrayOutputStream outStream) throws IOException{
        if(StringUtils.isEmpty(uri)) {
            return "";
        }
        try {
            if(uri.contains("127.0.0.1")&&!uri.contains("0x")){
                File file = new File(uri.replace("http://127.0.0.1:8801", "/opt/web/images"));
                if(file.exists()){
                    FileInputStream inputStream = new FileInputStream(file);
                    byte b[] = new byte[1024];
                    String contentType = file.getName();
                    int count = -1;  
                    while ((count = inputStream.read(b, 0, 1024)) != -1) {
                        outStream.write(b, 0, count);  
                    }
                    b = null;  
                    inputStream.close();
                    return contentType;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        URL url = new URL(uri);
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setConnectTimeout(10000);
        uc.setReadTimeout(15000);
        uc.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");
        uc.connect();
        if(uc.getResponseCode()>400){
            System.out.println(uc.getResponseCode());
            return "";
        }
        InputStream is = uc.getInputStream();
        byte b[] = new byte[1024];
        String contentType = uc.getContentType();
        int count = -1;  
        while ((count = is.read(b, 0, 1024)) != -1) {
            outStream.write(b, 0, count);  
        }
        b = null;  
        is.close();
        uc.disconnect();
        return contentType;
    }
    
    public static String moveImage(String url,String topath) {
        try {
            if(topath.charAt(0)!='/') {
                topath = "/"+topath;
            }
            topath = new SimpleDateFormat("yyyy-MM").format(new Date())+topath;
            String paths[] = topath.split("\\/");
            String pathPre = "/opt/web/images/";
            url = url.replace("http://pic.test.com/", pathPre);
            if(url.startsWith("http")) {
                return url;
            }
            String path = pathPre+"1";
            for(int i=0;i<paths.length;i++){
                if(!StringUtils.isEmpty(paths[i])){
                    path = path + "/" + paths[i];
                }
            }
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            
            File sourceFile = new File(url);
            if(!sourceFile.exists()) {
                return "";
            }
            path = path + "/"+sourceFile.getName();
            
            if(sourceFile.renameTo(new File(path))) {
                return path.replace(pathPre, "http://pic.test.com/");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    public static String uploadImage(String serveLoadPath,String suffix,byte imageData[]){
        try {
            
            if(imageData.length<100) {
                return "";
            }
            
            long milis = System.currentTimeMillis();
            String paths[] = serveLoadPath.split("\\/");
            String pathPre = "/opt/web/images/";
            String path = pathPre+"1";
            for(int i=0;i<paths.length;i++){
                if(!StringUtils.isEmpty(paths[i])){
                    path = path + "/" + paths[i];
                }
            }
            
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            
            path = path + "/n_"+(int)(Math.random()*10000)+""+milis+"." + suffix;
            
            file = new File(path);
            
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(imageData);
            outputStream.flush();
            outputStream.close();
            
            return path.replace(pathPre, "http://pic.test.com/");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    public static void deleteImage(String url) throws Exception{
        url = url.replace("http://pic.test.com", "/opt/web/images");
        if(url.startsWith("http")) {
            return;
        }
        File file = new File(url);
        if(file.exists()&&!file.isDirectory()){
            file.delete();
        }
    }
    
    public static String getUploadImages(HttpServletRequest request,String uppath,boolean ismuti) throws Exception{
        boolean isMultipart = UploadRequest.isMultipart(request);
        String imgString = "";
        if (isMultipart) {//上传
            UploadRequest uploadRequest = ((UploadRequest) request);
            Iterator<String> filenames  = uploadRequest.getFileNames();
            while(filenames!=null && filenames.hasNext()){
                List<RequestFile> files = uploadRequest.getFiles(filenames.next());
                for (int i = 0; i < files.size(); i++) {
                    byte fileStream[] = files.get(i).getBytes();
                    try {
                        if(fileStream.length>0){
                            fileStream = ImagesUtil.processUploadImage(fileStream,1000);
                            if(fileStream.length>0){
                                String tempImg = ImagesUtil.uploadImage(new SimpleDateFormat("yyyy-MM").format(new Date())+"/"+uppath, "jpg", fileStream);
                                if (!StringUtils.isEmpty(tempImg)) {
                                    imgString = tempImg + ",";
                                    if(!ismuti){
                                        break;
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if(!ismuti){
                    break;
                }
            }
            if(imgString.length()>0){
                imgString = imgString.substring(0, imgString.length()-1);
            }
        }
        return imgString;
    }
    
    public static String downloadAndUpload(String url,String uppath) throws Exception{
        if(!StringUtils.isEmpty(url)) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            downloadImage(url, outStream);
            byte imageBytes[] = outStream.toByteArray();
            if(imageBytes.length>0){
                return ImagesUtil.uploadImage(new SimpleDateFormat("yyyy-MM").format(new Date())+"/"+uppath, "jpg", imageBytes);
            }
        }
        return null;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值