Java 下载远程图片到本地

……………………
    public static void downloadImg(String imgUrl,String fileName) {
        final String DocumentName = fileName;
        final String DocumentPath = "imgs"+File.separator;
        final String DownloadURL = imgUrl;

        try {
            //自动创建文件夹
            File file = new File(DocumentPath);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
            //解析下载地址
            URL url = new URL(DownloadURL);
            URLConnection cnt = url.openConnection();
            InputStream inStream = cnt.getInputStream();
            FileOutputStream fos = new FileOutputStream(DocumentPath + DocumentName);
            int bytesum = 0;
            int byteread;
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fos.write(buffer, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
……………………

Java 下载远程图片到本地

Java 解析URL参数

……………………
    public static String getUrlparameter(String url, String name) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(url);
        if (matcher.find()) {
            return matcher.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }
……………………

Java 解析URL参数

Java 本地文件上传FTP服务器

    ……………………
      public static void uploadFtp(String url, int port, String username, String password, String remoteFilePath, String localFilePath){
        FTPClient ftpClient = new FTPClient();
        File localFile = new File(localFilePath);
        try {
            ftpClient.connect(url, port);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
 
            FileInputStream inputStream = new FileInputStream(localFile);
 
            ftpClient.storeFile(remoteFilePath, inputStream);
 
            inputStream.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (localFile.exists()) {
		if(!localFile.delete()){
		    //System.out.println("本地文件删除失败,请手动删除imgs文件夹内的全部文件");
		}
	    }
        }
    }
……………………

Java 本地文件上传FTP服务器

Java 修改图片尺寸

……………………
    public static void compressImg(String filePath, String ext) throws Exception {
    	int newWidth = 160;
    	int newHeight = 160;
    
    	File imgFile = new File(filePath);
    	BufferedImage image = ImageIO.read(imgFile);
    	int width = image.getWidth();
	int height = image.getHeight();
	if(Math.abs(width-height)==0){
		BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
		Graphics2D g = newImage.createGraphics();
		g.drawImage(image, 0, 0, newWidth, newHeight, null);
		g.dispose();
		ImageIO.write(newImage, ext, new File(filePath));
	}
    }
……………………

Java 修改图片尺寸

Java Unicode类

public class UnicodeUtil {
	//字符串转换unicode
    public static String stringToUnicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);  // 取出每一个字符
            unicode.append("\\u" +Integer.toHexString(c));// 转换为unicode
        }
        return unicode.toString();
    }

    //unicode 转字符串
    public static String unicodeToString(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);// 转换出每一个代码点
            string.append((char) data);// 追加成string
        }
        return string.toString();
    }
}

Java Unicode类

JAVA 图片拼接

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class MergeImageUtil {
	/**
	 * 拼接图片(注:图片需长宽一致)
	 * @param files  img1 ,img2
	 * @param type  1:横向拼接 2:纵向拼接
	 * @param targetFile 合成新的图片地址
	 */
	public static void mergeImage(String[] files, int type, String targetFile) {
		int len = files.length;
		if (len < 1) {
			throw new RuntimeException("图片数量小于1");
		}
		File[] src = new File[len];
		BufferedImage[] images = new BufferedImage[len];
		int[][] ImageArrays = new int[len][];
		for (int i = 0; i < len; i++) {
			try {
				src[i] = new File(files[i]);
				images[i] = ImageIO.read(src[i]);
			}
			catch (Exception e) {
				throw new RuntimeException(e);
			}
			int width = images[i].getWidth();
			int height = images[i].getHeight();
			ImageArrays[i] = new int[width * height];
			ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
		}
		int newHeight = 0;
		int newWidth = 0;
		for (int i = 0; i < images.length; i++) {
			// 横向
			if (type == 1) {
				newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
				newWidth += images[i].getWidth();
			} else if (type == 2) {
				// 纵向
				newWidth = newWidth > images[i].getWidth() ? newWidth : images[i].getWidth();
				newHeight += images[i].getHeight();
			}
		}
		if (type == 1 && newWidth < 1) {
			return;
		}
		if (type == 2 && newHeight < 1) {
			return;
		}
		// 生成新图片
		try {
			BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
			int height_i = 0;
			int width_i = 0;
			for (int i = 0; i < images.length; i++) {
				if (type == 1) {
					ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0,
						      images[i].getWidth());
					width_i += images[i].getWidth();
				} else if (type == 2) {
					ImageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), ImageArrays[i], 0, newWidth);
					height_i += images[i].getHeight();
				}
			}
			//输出想要的图片
			ImageIO.write(ImageNew, targetFile.split("\\.")[1], new File(targetFile));
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

JAVA 图片拼接

Java 身份证信息处理类

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


/**
 * @author QiFeng·Luo
 */
public class IDCardUtil {

    /**
     * 数字
     */
    public final static Pattern NUMBERS = Pattern.compile("\\d+");

    /**
     * 中国公民身份证号码最小长度。
     */
    private static final int CHINA_ID_MIN_LENGTH = 15;

    /**
     * 中国公民身份证号码最大长度。
     */
    private static final int CHINA_ID_MAX_LENGTH = 18;

    public static Exception isValidatedAllIdcard(String idcard) throws Exception {
        boolean ret = isIdcard(idcard);
        if (!ret) {
            throw new Exception("身份证格式有误");
        }
        return null;
    }

    final static Map<Integer, String> zoneNum = new HashMap<>();
    /**
     * 身份证省份编码
     * */
    static {
        zoneNum.put(11, "北京");
        zoneNum.put(12, "天津");
        zoneNum.put(13, "河北");
        zoneNum.put(14, "山西");
        zoneNum.put(15, "内蒙古");
        zoneNum.put(21, "辽宁");
        zoneNum.put(22, "吉林");
        zoneNum.put(23, "黑龙江");
        zoneNum.put(31, "上海");
        zoneNum.put(32, "江苏");
        zoneNum.put(33, "浙江");
        zoneNum.put(34, "安徽");
        zoneNum.put(35, "福建");
        zoneNum.put(36, "江西");
        zoneNum.put(37, "山东");
        zoneNum.put(41, "河南");
        zoneNum.put(42, "湖北");
        zoneNum.put(43, "湖南");
        zoneNum.put(44, "广东");
        zoneNum.put(45, "广西");
        zoneNum.put(46, "海南");
        zoneNum.put(50, "重庆");
        zoneNum.put(51, "四川");
        zoneNum.put(52, "贵州");
        zoneNum.put(53, "云南");
        zoneNum.put(54, "西藏");
        zoneNum.put(61, "陕西");
        zoneNum.put(62, "甘肃");
        zoneNum.put(63, "青海");
        zoneNum.put(64, "宁夏");
        zoneNum.put(65, "新疆");
        zoneNum.put(71, "台湾");
        zoneNum.put(81, "香港");
        zoneNum.put(82, "澳门");
        zoneNum.put(91, "国外");
    }

    /**
     * 校验码
     */
    final static int[] PARITYBIT = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };

    /**
     * 加权因子wi
     */
    final static int[] POWER_LIST = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

    /**
     * 验证身份证号有效性
     *
     * @param idCard:身份证号
     * @return true/false
     */
    public static boolean isIdcard(String idCard) {
        // 号码长度应为15位或18位
        if (idCard == null || (idCard.length() != 15 && idCard.length() != 18)) {
            return false;
        }
        // 校验区位码
        if (!zoneNum.containsKey(Integer.valueOf(idCard.substring(0, 2)))) {
            return false;
        }
        // 校验年份
        String year = idCard.length() == 15 ? "19" + idCard.substring(6, 8) : idCard.substring(6, 10);
        final int iyear = Integer.parseInt(year);
        if (iyear < 1900 || iyear > Calendar.getInstance().get(Calendar.YEAR)) {
            // 1900年的PASS,超过今年的PASS
            return false;
        }
        // 校验月份
        String month = idCard.length() == 15 ? idCard.substring(8, 10) : idCard.substring(10, 12);
        final int imonth = Integer.parseInt(month);
        if (imonth < 1 || imonth > 12) {
            return false;
        }
        // 校验天数
        String day = idCard.length() == 15 ? idCard.substring(10, 12) : idCard.substring(12, 14);
        final int iday = Integer.parseInt(day);
        if (iday < 1 || iday > 31) {
            return false;
        }
        // 校验一个合法的年月日
        if (!isValidDate(year + month + day)) {
            return false;
        }
        // 校验位数
        int power = 0;
        final char[] cs = idCard.toUpperCase().toCharArray();
        for (int i = 0; i < cs.length; i++) {// 循环比正则表达式更快
            if (i == cs.length - 1 && cs[i] == 'X') {
                break;// 最后一位可以是X或者x
            }
            if (cs[i] < '0' || cs[i] > '9') {
                return false;
            }
            if (i < cs.length - 1) {
                power += (cs[i] - '0') * POWER_LIST[i];
            }
        }
        // 校验“校验码”
        if (idCard.length() == 15) {
            return true;
        }
        return cs[cs.length - 1] == PARITYBIT[power % 11];
    }

    /**
     * 判断字符串是否为日期格式(合法)
     *
     * @param inDate:字符串时间
     * @return true/false
     */
    public static boolean isValidDate(String inDate) {
        if (inDate == null) {
            return false;
        }
        // 或yyyy-MM-dd
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd");
        if (inDate.trim().length() != dataFormat.toPattern().length()) {
            return false;
        }
        // 该方法用于设置Calendar严格解析字符串;默认为true,宽松解析
        dataFormat.setLenient(false);
        try {
            dataFormat.parse(inDate.trim());
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * 转换成日期
     * @param birthday
     * @return
     */
    private static Date toBirthDay(String birthday){
        try{
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, Integer.parseInt(birthday.substring(0, 4)));
            // 月份从0开始,所以减1
            calendar.set(Calendar.MONTH, Integer.parseInt(birthday.substring(4, 6)) - 1);
            calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(birthday.substring(6, 8)));
            // 以下设置时分秒,但是对生日的意义不大
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            return calendar.getTime();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 给定内容是否匹配正则
     *
     * @param pattern 模式
     * @param content 内容
     * @return 正则为null或者""则不检查,返回true,内容为null返回false
     */
    private static boolean isMatch(Pattern pattern, CharSequence content) {
        if (content == null || pattern == null) {
            // 提供null的字符串为不匹配
            return false;
        }
        return pattern.matcher(content).matches();
    }

    /**
     * 将字符串转换成指定格式的日期
     *
     * @param str        日期字符串.
     * @param dateFormat 日期格式. 如果为空,默认为:yyyy-MM-dd HH:mm:ss.
     * @return
     */
    private static Date strToDate(final String str, String dateFormat) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        try {
            if (dateFormat == null || dateFormat.length() == 0) {
                dateFormat = "yyyy-MM-dd HH:mm:ss";
            }
            DateFormat fmt = new SimpleDateFormat(dateFormat);
            return fmt.parse(str.trim());
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 根据日期获取年
     *
     * @param date 日期
     * @return 年的部分
     */
    public static int year(Date date) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        return ca.get(Calendar.YEAR);
    }

    /**
     * 将power和值与11取模获得余数进行校验码判断
     *
     * @param iSum 加权和
     * @return 校验位
     */
    private static char getCheckCode18(int iSum) {
        switch (iSum % 11) {
            case 10:
                return '2';
            case 9:
                return '3';
            case 8:
                return '4';
            case 7:
                return '5';
            case 6:
                return '6';
            case 5:
                return '7';
            case 4:
                return '8';
            case 3:
                return '9';
            case 2:
                return 'x';
            case 1:
                return '0';
            case 0:
                return '1';
            default:
                return ' ';
        }
    }

    /**
     * 获得18位身份证校验码
     * 计算方式:
     * 将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
     * 将这17位数字和系数相乘的结果相加
     * 用加出来和除以11,看余数是多少
     * 余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2
     * 通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2
     * @param code17 18位身份证号中的前17位
     * @return 第18位
     */
    private static char getCheckCode18(String code17) {
        int sum = getPowerSum(code17.toCharArray());
        return getCheckCode18(sum);
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后,再得到和值
     *
     * @param iArr 身份证号码的数组
     * @return 身份证编码
     */
    private static int getPowerSum(char[] iArr) {
        int iSum = 0;
        if (POWER_LIST.length == iArr.length) {
            for (int i = 0; i < iArr.length; i++) {
                iSum += Integer.valueOf(String.valueOf(iArr[i])) * POWER_LIST[i];
            }
        }
        return iSum;
    }

    /**
     * 将15位身份证号码转换为18位
     *
     * @param idCard 15位身份编码
     * @return 18位身份编码
     */
    public static String convertIdCard(String idCard) {
        StringBuilder idCard18;
        if (idCard.length() != CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (isMatch(NUMBERS, idCard)) {
            // 获取出生年月日
            String birthday = idCard.substring(6, 12);
            Date birthDate = strToDate(birthday, "yyMMdd");
            // 获取出生年
            int sYear = year(birthDate);
            // 理论上2000年之后不存在15位身份证,可以不要此判断
            if (sYear > 2000) {
                sYear -= 100;
            }
            idCard18 = new StringBuilder().append(idCard, 0, 6).append(sYear).append(idCard.substring(8));
            // 获取校验位
            char sVal = getCheckCode18(idCard18.toString());
            idCard18.append(sVal);
        } else {
            return null;
        }
        return idCard18.toString();
    }

    /**
     * 从身份证号码中获取生日
     * @param idno
     * @return null表示idno错误,未获取到生日
     */
    public static Date getBirthDay(String idno){
        if(!isIdcard(idno)){
            return null;
        }
        if (idno.length() == 15) {
            // 如果是15位转为18位
            idno = convertIdCard(idno);
        }
        return toBirthDay(idno.substring(6, 14));
    }

    /**
     * 从身份证号码中获取生日
     * @param idno
     * @return null表示idno错误,未获取到生日 日期格式为:yyyy-MM-dd
     */
    public static String getBirthDayStr(String idno){
        if(!isIdcard(idno)){
            return null;
        }
        if (idno.length() == 15) {
            // 如果是15位转为18位
            idno = convertIdCard(idno);
        }
        Date birthday = toBirthDay(idno.substring(6, 14));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(birthday);
    }
    /**
     * 从身份证号中获取性别
     * @param idno
     * @return 0:男,1:女,-1:证件号码错误
     */
    public static String getGender(String idno){
        if(!isIdcard(idno)){
            return "-1";
        }
        if (idno.length() == 15) {
            // 如果是15位转为18位
            idno = convertIdCard(idno);
        }
        // 奇男,偶女
        return (Integer.parseInt(idno.substring(16, 17)) % 2) == 0 ? "1" : "0";
    }

    /**
     * 方法调用测试
     * */
    public static void main(String[] args) {
        String idc= "130503670401001";
        //检查身份证是否合规
        boolean idcard = isIdcard(idc);
        if (idcard) {
            System.out.println("身份证号码合规");
            // 获取身份证号码中的生日
            Date birthDay = getBirthDay(idc);
            System.out.println("当前身份证的生日为:"+ getBirthDayStr(idc));
            // 获取性别
            String gender = getGender(idc);
            if ("0".equals(gender)) {
                System.out.println("当前身份证的性别为:男性");
            } else if ("1".equals(gender)) {
                System.out.println("当前身份证的性别为:女性");
            } else {
                System.out.println("当前身份证格式不正确");
            }
        }else {
            System.out.println("身份证格式有误");
        }
    }

}


Java 身份证信息处理类

Java Canny边缘检测

import java.awt.image.BufferedImage;

public class CannyUtil {
	int Y;
	int X;
	int src[][];
	int dest[][];
	double tan[][];
	BufferedImage bufferedImage;
	BufferedImage bufferedImage_old;
	public CannyUtil(BufferedImage bi) {
		bufferedImage_old = bi;
		bufferedImage = bi;
		Y = bi.getWidth();
		X = bi.getHeight();
		src = new int[Y][X];
		dest = new int[Y][X];
		tan = new double[Y][X];
	}
	
	//灰度
	public BufferedImage Gray() {
		for(int y=0;y<Y;y++) {
			for(int x=0;x<X;x++) {
				int r=(bufferedImage.getRGB(y,x)>>16)&0x000000ff;
		    	int g=(bufferedImage.getRGB(y,x)>>8)&0x000000ff;
		    	int b=bufferedImage.getRGB(y,x)&0x000000ff;
		    	src[y][x]=(int)(0.2989*r+0.587*g+0.114*b);
				//bufferedImage.setRGB(y,x,0xff000000|src[y][x]|(src[y][x]<<8)|(src[y][x]<<16));
			}
		}
		return bufferedImage;
	}
	
	//高斯平滑
	public BufferedImage Gauss()
	{
		int M[][]={{1,2,1},{2,4,2},{1,2,1}};
    	bufferedImage=new BufferedImage(Y,X,BufferedImage.TYPE_INT_RGB);
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
			{
				dest[y][x]= src[y-1][x-1]*M[0][0]+src[y][x-1]*M[1][0]+src[y+1][x-1]*M[2][0]
						+src[y-1][x]  *M[0][1]+src[y][x]  *M[1][1]+src[y+1][x]  *M[2][1]
						+src[y-1][x+1]*M[0][2]+src[y][x+1]*M[1][2]+src[y+1][x+1]*M[2][2];
				dest[y][x]/=16;
				bufferedImage.setRGB(y,x,0xff000000|dest[y][x]|(dest[y][x]<<8)|(dest[y][x]<<16));
			}
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
				src[y][x]=dest[y][x];
		return bufferedImage;
	}
	//索贝尔边缘提取
	public BufferedImage Sobel()
    {
    	int Mx[][]={{-1,0,1},{-2,0,2},{-1,0,1}};
    	int My[][]={{-1,-2,-1},{0,0,0},{1,2,1}};
    	bufferedImage=new BufferedImage(Y,X,BufferedImage.TYPE_INT_RGB);
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
			{
				int dx=	 src[y-1][x-1]*Mx[0][0]+src[y][x-1]*Mx[1][0]+src[y+1][x-1]*Mx[2][0]
						+src[y-1][x]  *Mx[0][1]+src[y][x]  *Mx[1][1]+src[y+1][x]  *Mx[2][1]
						+src[y-1][x+1]*Mx[0][2]+src[y][x+1]*Mx[1][2]+src[y+1][x+1]*Mx[2][2];
				int dy=	 src[y-1][x-1]*My[0][0]+src[y][x-1]*My[1][0]+src[y+1][x-1]*My[2][0]
						+src[y-1][x]  *My[0][1]+src[y][x]  *My[1][1]+src[y+1][x]  *My[2][1]
						+src[y-1][x+1]*My[0][2]+src[y][x+1]*My[1][2]+src[y+1][x+1]*My[2][2];
				dest[y][x]=(int)(Math.sqrt(dx*dx+dy*dy)+0.5);
				if(dest[y][x]>255) dest[y][x]=255;
				if(dest[y][x]<0) dest[y][x]=0;
				bufferedImage.setRGB(y,x,0xff000000|dest[y][x]|(dest[y][x]<<8)|(dest[y][x]<<16));
				tan[y][x]=1.0*dy/dx;
			}
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
				src[y][x]=dest[y][x];
		return bufferedImage;
    }
    //非极大值抑制
	public BufferedImage NMS()
	{
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
			{
				if(Math.abs(tan[y][x])<=0.5)
				{
					if(src[y][x]>=src[y][x-1]&&src[y][x]>=src[y][x+1])
						dest[y][x]=src[y][x];
					else
						dest[y][x]=0;
				}
				else if(-2<=tan[y][x]&&tan[y][x]<=-0.5)
				{
					if(src[y][x]>=src[y+1][x-1]&&src[y][x]>=src[y-1][x+1])
						dest[y][x]=src[y][x];
					else
						dest[y][x]=0;
				}
				else if(0.5<=tan[y][x]&&tan[y][x]<=2)
				{
					if(src[y][x]>=src[y-1][x-1]&&src[y][x]>=src[y+1][x+1])
						dest[y][x]=src[y][x];
					else
						dest[y][x]=0;
				}
				else if(2<=Math.abs(tan[y][x]))
				{
					if(src[y][x]>=src[y-1][x]&&src[y][x]>=src[y+1][x])
						dest[y][x]=src[y][x];
					else
						dest[y][x]=0;
				}
				bufferedImage.setRGB(y,x,0xff000000|dest[y][x]|(dest[y][x]<<8)|(dest[y][x]<<16));
			}
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
				src[y][x]=dest[y][x];
		return bufferedImage;
	}
	//双阈值连接
	public BufferedImage DT()
	{
		int th1=127;
		int th2=63;
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
			{
				if(src[y][x]>=th1)
					dest[y][x]=255;
				else if(src[y][x]<=th2)
					dest[y][x]=0;
				else
				{
					if(src[y-1][x-1]>=th1||src[y-1][x]>=th1||src[y-1][x+1]>=th1||src[y][x-1]>=th1||src[y][x+1]>=th1||src[y+1][x-1]>=th1||src[y+1][x]>=th1||src[y+1][x+1]>=th1)
						dest[y][x]=255;
					else
						dest[y][x]=0;
				}	
				bufferedImage.setRGB(y,x,0xff000000|dest[y][x]|(dest[y][x]<<8)|(dest[y][x]<<16));
			}
		for(int y=1;y<Y-1;y++)
			for(int x=1;x<X-1;x++)
				src[y][x]=dest[y][x];
		return bufferedImage;
	}
	
	//自动裁剪
	public BufferedImage autoClip(int GaussCount) {
		bufferedImage = Gray();
		for(int i=0;i<GaussCount;i++) {
			bufferedImage = Gauss();
		}
		bufferedImage = Sobel();		
		bufferedImage = NMS();
		bufferedImage = DT();
		
		boolean minXb = false, minYb = false;
	    int minX = 0, minY = 0, maxX = 0, maxY = 0;
	    
		for (int x = 0; x < bufferedImage.getWidth(); x++) {
	        for (int y = 0; y < bufferedImage.getHeight(); y++) {
	            // 如果是透明像素 跳过
	            if (bufferedImage.getRGB(x,y) == 0) continue;

	            // 获取该点像素,并以object类型表示
	            Object data = bufferedImage.getRaster().getDataElements(x, y, null);
	            int r = bufferedImage.getColorModel().getRed(data);
	            int g = bufferedImage.getColorModel().getGreen(data);
	            int b = bufferedImage.getColorModel().getBlue(data);
	            
	            if (r == 0 && g == 0 && b == 0) continue;

	            if (!minXb) {
	                minX = x;
	                minXb = true;
	            }

	            if (!minYb) {
	                minY = y;
	                minYb = true;
	            }

	            minX = Math.min(minX, x);
	            minY = Math.min(minY, y);

	            maxX = Math.max(maxX, x);
	            maxY = Math.max(maxY, y);
	        }
	    }
		System.out.printf("minX=%d,minY=%d,maxX=%d,maxY=%d\n", minX,minY,maxX,maxY);
		return bufferedImage_old.getSubimage(minX, minY, maxX - minX, maxY - minY);
	}
}

Java Canny边缘检测

Java 文件操作工具类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;

import com.bcap_systemlib.config.Configuration;

public class FileUtil {
    /**
     * 将多个文件打包到一个zip中
     *
     * @param sourceFolder
     * @param zipFile
     * @return
     * @throws Exception 
     */
    public static boolean zipFile(String sourceFolder, File zipFile) throws Exception{
        boolean isOk = true;
        File f = new File(sourceFolder);
        ZipOutputStream out = null;
        try{
            if(!f.exists()){
                f.mkdirs();
            }
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            zip(out, f, "");
            out.flush();
            FileUtils.deleteDirectory(f);
        } catch (Exception e){
            e.printStackTrace();
            throw new Exception("压缩文件出错!");
        } finally
        {
            if(null != out){
                try{ out.close(); } catch (Exception e){ e.printStackTrace();}
            }
        }
        return isOk;
    }

    /**
     * 递归压缩文件
     * @param out
     * @param f
     * @param base
     * @throws Exception
     */
    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[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();
        }
    }

    /**
     * 下载单个文件
     *
     * @param file
     * @param request
     * @param response
     * @return
     */
    public static boolean downFile(File file, HttpServletRequest request, HttpServletResponse response) {
        boolean isOk = true;
        OutputStream myout = null;
        FileInputStream fis = null;
        BufferedInputStream buff = null;
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute("state", "");
        }
        try {
            response.setContentType("application/x-msdownload");
            response.setContentLength((int) file.length());
            response.setHeader("content-disposition", "attachment;filename=" + EncodingConvertUtil.utf2iso(file.getName()));
            fis = new FileInputStream(file);
            buff = new BufferedInputStream(fis);
            byte[] b = new byte[1024 * 10];//相当于我们的缓存
            long k = 0;//该值用于计算当前实际下载了多少字节
            //从response对象中得到输出流,准备下载
            myout = response.getOutputStream();
            while (k < file.length()) {
                int j = buff.read(b, 0, b.length);
                k += j;
                //将b中的数据写到客户端的内存
                myout.write(b, 0, j);
            }
            myout.flush();
        } catch (Exception e) {
            e.printStackTrace();
            isOk = false;
        } finally {
            try {
                if (null != myout) {
                    myout.close();
                    myout = null;
                }
                if (null != buff) {
                    buff.close();
                    buff = null;
                }
                if (null != fis) {
                    fis.close();
                    fis = null;
                }
                if(file.exists()){
                    FileUtil.delFile(file);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return isOk;
    }

    /**
     * 删除单个文件
     *
     * @param file
     * @return
     */
    public static boolean delFile(File file) {
        boolean isOk = true;
        try {
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            isOk = false;
        } finally {
            // log ...
        }
        return isOk;
    }
    
    public static void downloadFileFromRemote(String remoteFilePath, String localFilePath){
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try
        {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1)
            {
                bos.write(b, 0, len);
            }
            System.out.println("下载成功");
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bis.close();
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    public static void writeFile(String filePathAndName, String fileContent) {
    	try {
    		File f = new File(filePathAndName);
    		if (!f.exists()) {
    			f.createNewFile();
    		}
    		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),Configuration.SERVLET_CHARACTER_ENCODING);
    		BufferedWriter writer=new BufferedWriter(write);   
    		writer.write(fileContent);
    		writer.close();
    	} catch (Exception e) {
			System.out.println("写文件内容操作出错");
			e.printStackTrace();
    	}
    }
    
    public static String readFile(String filePathAndName) {
    	String fileContent = "";
    	try {  
    		File f = new File(filePathAndName);
    		if(f.isFile()&&f.exists()){
    			InputStreamReader read = new InputStreamReader(new FileInputStream(f),Configuration.SERVLET_CHARACTER_ENCODING);
    			BufferedReader reader=new BufferedReader(read);
    			String line;
    			while ((line = reader.readLine()) != null) {
    				fileContent += line;
    			}   
    			read.close();
    		}
    	} catch (Exception e) {
    		System.out.println("读取文件内容操作出错");
    		e.printStackTrace();
    	}
    	return fileContent;
    }
    
    public static String getExtName(String filename) {
        int index = filename.lastIndexOf(".");
 
        if (index == -1) {
            return null;
        }
        String result = filename.substring(index);
        return result;
    }
}

Java 文件操作工具类

Java实现Escape

public class EscapeUtil {  
	public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	public static String isoToGB(String src) {
		String strRet = null;
		try {
			strRet = new String(src.getBytes("ISO_8859_1"), "GB2312");
		} catch (Exception e) {

		}
		return strRet;
	}

	public static String isoToUTF(String src) {
		String strRet = null;
		try {
			strRet = new String(src.getBytes("ISO_8859_1"), "UTF-8");
		} catch (Exception e) {

		}
		return strRet;
	}
 
	 public static String escape(String src) {
			int i;
			char j;
			StringBuffer tmp = new StringBuffer();
			tmp.ensureCapacity(src.length() * 6);
			for (i = 0; i < src.length(); i++) {
				j = src.charAt(i);
				if (Character.isDigit(j) || Character.isLowerCase(j)
						|| Character.isUpperCase(j))
					tmp.append(j);
				else if (j < 256) {
					tmp.append("%");
					if (j < 16)
						tmp.append("0");
					tmp.append(Integer.toString(j, 16));
				} else {
					tmp.append("%u");
					tmp.append(Integer.toString(j, 16));
				}
			}
			return tmp.toString();
		}
}

Java实现Escape