Google的图片处理库和条码处理库、汉字转拼音库

Google的图片处理库和条码处理库、汉字转拼音库

Thumbnailator

Thumbnailator 是一个优秀的图片处理的Google开源Java类库。处理效果远比Java API的好。从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生成处理后的图片,且允许微调图片的生成方式,同时保持了需要写入的最低限度的代码量。还支持对一个目录的所有图片进行批量处理操作。

Thumbnailator Github

支持的处理操作:图片缩放,区域裁剪,水印,旋转,保持比例。
另外值得一提的是,Thumbnailator至今仍不断更新,怎么样,感觉很有保障吧!

引入库

    // https://mvnrepository.com/artifact/net.coobird/thumbnailator
    compile group: 'net.coobird', name: 'thumbnailator', version: '0.4.8'

原图
在这里插入图片描述
加水印

    @Test
    public void testThumbnailitor(){
        try {
            Thumbnails.of("F:\\images\\img1.jpg")
                    .size(1280, 1024)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("F:\\images\\watermark.jpg")), 0.5f)
                    .outputQuality(0.8f)
                    .toFile("F:\\images\\imgtemp.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Thumbnails.of("F:\\images\\img1.jpg")
                    .size(1280, 1024)
                    .watermark(Positions.CENTER, ImageIO.read(new File("F:\\images\\watermark.jpg")), 0.5f)
                    .outputQuality(0.8f)
                    .toFile("F:\\images\\imgtemp2.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述
保持比例缩小图片

            Thumbnails.of("F:\\images\\img1.jpg")
                    .size(120, 100)
                    .toFile("F:\\images\\imgtemp3.jpg");

在这里插入图片描述
旋转图片

            Thumbnails.of("F:\\images\\img1.jpg")
                    .size(800, 800)
                    .rotate(90)
                    .toFile("F:\\images\\imgtemp4.jpg");

            Thumbnails.of("F:\\images\\img1.jpg")
                    .size(800, 800)
                    .rotate(-45)
                    .toFile("F:\\images\\imgtemp5.jpg");

在这里插入图片描述
降低图片质量压缩图片

            Thumbnails.of("F:\\images\\img1.jpg")
                    .scale(1)
                    .outputQuality(0.1)
                    .toFile("F:\\images\\imgtemp6.jpg");

在这里插入图片描述

zxing

ZXing是一个Google开发开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。该项目可实现的条形码编码和解码。目前支持以下格式:QR码、UPC-A、UPC-E、EAN-8,EAN-13、39码、93码、代码128、RSS-14(所有的变体)、RSS扩展(大多数变体)、数据矩阵;

zxing Github

加入引用

    // https://mvnrepository.com/artifact/com.google.zxing/core
    compile group: 'com.google.zxing', name: 'core', version: '3.4.0'
// https://mvnrepository.com/artifact/com.google.zxing/javase
    compile group: 'com.google.zxing', name: 'javase', version: '3.4.0'

生成一个二维码到文件

String filePath = "D://";
        String fileName = "zxing.png";
        JSONObject json = new JSONObject();
        json.put("title" ,   "https://www.baidu.com");
        json.put("author", "shihy");
        String content = json.toJSONString();// 内容
        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;// 生成矩阵
        try {
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像

            System.out.println("输出成功.");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

在这里插入图片描述
在这里插入图片描述
从文件解析二维码内容

      String filePath = "D://zxing.png";
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            JSONObject content = JSONObject.parseObject(result.getText());
            System.out.println("图片中内容:  ");
            System.out.println("author: " + content.getString("author"));
            System.out.println("zxing:  " + content.getString("title"));
            System.out.println("图片中格式:  ");
            System.out.println("encode: " + result.getBarcodeFormat());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

在这里插入图片描述
生成二维码到OutputStream里,在网页显示

public class QuickResponse {

    public  static BitMatrix generateQRCodeByJson(JSONObject json , int imgWidth , int imgHeight ,String imgformat) {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;// 生成矩阵
        try {
            bitMatrix = new MultiFormatWriter().encode(json.toJSONString(),
                    BarcodeFormat.QR_CODE, imgWidth, imgHeight, hints);
            return bitMatrix;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static BitMatrix generateQRCodeByString(String content , int imgWidth , int imgHeight ,String imgformat){
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;// 生成矩阵
        try {
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, imgWidth, imgHeight, hints);
            return bitMatrix;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decodeQRCode(String filePath){
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            return result.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
    @RequestMapping("/generate")
    public String generateQRcodePicture(HttpServletResponse response){
         BitMatrix bitMatrix = QuickResponse.generateQRCodeByString("http://www.baidu.com", 120, 120, "png");
        try {
            MatrixToImageWriter.writeToStream(bitMatrix ,"png" ,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }
    
    @RequestMapping("/other")
    public String useQRcode(){
        return "otherpage";
    }
在这里插入代码片
<body>
<h2>see you</h2>
<img src="/generate" width="100px" height="100px" >
</body>

在这里插入图片描述
在这里插入图片描述

JPinyin 汉字转拼音的Java类库

JPinyin是一个汉字转拼音的Java开源类库,在PinYin4j的功能基础上做了一些改进。
【JPinyin主要特性】
1、准确、完善的字库;
Unicode编码从4E00-9FA5范围及3007(〇)的20903个汉字中,JPinyin能转换除46个异体字(异体字不存在标准拼音)之外的所有汉字;
2、拼音转换速度快;
经测试,转换Unicode编码从4E00-9FA5范围的20902个汉字,JPinyin耗时约100毫秒。
3、多拼音格式输出支持;
JPinyin支持多种拼音输出格式:带音标、不带音标、数字表示音标以及拼音首字母输出格式;
4、常见多音字识别;
JPinyin支持常见多音字的识别,其中包括词组、成语、地名等;
5、简繁体中文转换

引入依赖

Maven依赖:

        <dependency>
            <groupId>com.github.stuxuhai</groupId>
            <artifactId>jpinyin</artifactId>
            <version>1.1.8</version>
        </dependency>

Gradle依赖:

// https://mvnrepository.com/artifact/com.github.stuxuhai/jpinyin
compile group: 'com.github.stuxuhai', name: 'jpinyin', version: '1.1.8'

使用示例

    @Test
    public void test6() throws PinyinException {

        String str = "你好世界,我叫吃鱼王正。";

        /**
         * 将字符串转换成相应格式的拼音
         *
         * Params:
         * str – 需要转换的字符串
         * separator – 拼音分隔符
         * pinyinFormat – 拼音格式:WITH_TONE_NUMBER--数字代表声调,WITHOUT_TONE--不带声调,WITH_TONE_MARK--带声调
         * Returns:
         * 字符串的拼音
         */
        String str1 = PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_MARK); // nǐ,hǎo,shì,jiè
        String str2 = PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_NUMBER); // ni3,hao3,shi4,jie4
        String str3 = PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITHOUT_TONE); // ni,hao,shi,jie

        /**
         * 获取字符串对应拼音的首字母
         *
         * Params:
         * str – 需要转换的字符串
         * Returns:
         * 对应拼音的首字母
         */
        String str4 = PinyinHelper.getShortPinyin(str); // nhsj

        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);

        /**
         * PinyinHelper.hasMultiPinyin('已')
         * 判断字符是否是多音字
         */
//        还 是多音字
        if( PinyinHelper.hasMultiPinyin('还')){
            System.out.println(" 还 :是多音字");
        }
//        王 是多音字
        if( PinyinHelper.hasMultiPinyin('王')){
            System.out.println(" 王 :是多音字");
        }
//        周 不是多音字
        if( PinyinHelper.hasMultiPinyin('周')){
            System.out.println(" 周 :是多音字");
        }

        /**
         * 将单个汉字转换成带声调格式的拼音
         *
         * Params:
         * c – 需要转换成拼音的汉字
         * Returns:
         * 字符串的拼音
         */
        String[] strArray = PinyinHelper.convertToPinyinArray('王');

        for (int i = 0; i < strArray.length; i++) {
            System.out.printf(strArray[i]+" , ");
        }

    }

结果输出

nǐ,hǎo,shì,jiè,,,wǒ,jiào,chī,yú,wáng,zhèng,。
ni3,hao3,shi4,jie4,,,wo3,jiao4,chi1,yu2,wang2,zheng4,。
ni,hao,shi,jie,,,wo,jiao,chi,yu,wang,zheng,。
nhsj,wjcywz。
 还 :是多音字
 王 :是多音字
wáng , wàng , 
发布了48 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wangxudongx/article/details/90485871