zoukankan      html  css  js  c++  java
  • 工具类图片处理工具类

    package com.jyc.common.utils.file;

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Arrays;

    import com.jyc.common.utils.StringUtils;
    import org.apache.poi.util.IOUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import com.jyc.common.config.RuoYiConfig;
    import com.jyc.common.constant.Constants;

    /**
    * 图片处理工具类
    *
    * @author jianyongchao
    */
    public class ImageUtils
    {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath)
    {
    InputStream is = getFile(imagePath);
    try
    {
    return IOUtils.toByteArray(is);
    }
    catch (Exception e)
    {
    log.error("图片加载异常 {}", e);
    return null;
    }
    finally
    {
    IOUtils.closeQuietly(is);
    }
    }

    public static InputStream getFile(String imagePath)
    {
    try
    {
    byte[] result = readFile(imagePath);
    result = Arrays.copyOf(result, result.length);
    return new ByteArrayInputStream(result);
    }
    catch (Exception e)
    {
    log.error("获取图片异常 {}", e);
    }
    return null;
    }

    /**
    * 读取文件为字节数据
    *
    * @param key 地址
    * @return 字节数据
    */
    public static byte[] readFile(String url)
    {
    InputStream in = null;
    ByteArrayOutputStream baos = null;
    try
    {
    if (url.startsWith("http"))
    {
    // 网络地址
    URL urlObj = new URL(url);
    URLConnection urlConnection = urlObj.openConnection();
    urlConnection.setConnectTimeout(30 * 1000);
    urlConnection.setReadTimeout(60 * 1000);
    urlConnection.setDoInput(true);
    in = urlConnection.getInputStream();
    }
    else
    {
    // 本机地址
    String localPath = "c:xxxxx";/** 上传路径 */
    String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
    in = new FileInputStream(downloadPath);
    }
    return IOUtils.toByteArray(in);
    }
    catch (Exception e)
    {
    log.error("获取文件路径异常 {}", e);
    return null;
    }
    finally
    {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(baos);
    }
    }
    }
  • 相关阅读:
    python基础===利用unittest进行测试用例执行的几种方式
    python基础===基于cv2的播放器
    python基础===对字符串进行左右中对齐
    python基础===拆分字符串,和拼接字符串
    移动端测试===从安卓手机截图到桌面的几行代码
    工具===激活xmind 8
    软件测试===测试用例基线结构
    python基础===猴子补丁
    python基础===数据伪造模块faker
    shell编程===执行shell脚本的四种方法
  • 原文地址:https://www.cnblogs.com/qq3245792286/p/15469674.html
Copyright © 2011-2022 走看看