乐趣区

关于java:通用工具方法图片

图片文件与字节数组字符串互转(Base64 编解码)

1. 图片文件转化为字节数组字符串,并对其进行 Base64 编码解决

参数 imgFile:图片文件

// 将图片文件转化为字节数组字符串,并对其进行 Base64 编码解决
    public static String imageToBase64ByLocal(String imgFile) {
        try {
            InputStream in = null;
            byte[] data = null;
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            // 对字节数组 Base64 编码
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回 Base64 编码过的字节数组字符串
            return encoder.encode(data);

        } catch (IOException e) {System.out.println(e);
        }
        return null;
    }

运行后果:

2. 字节数组字符串转换为图片文件,并进行 Base64 解码

参数 imgStr: 待转换的字节数组字符串
参数 imgFilePath:转换后的图片寄存地址

public static boolean base64ToImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行 Base64 解码并生成图片
        // 图像数据为空
        if (isEmpty(imgStr)) {return false;}
        try {BASE64Decoder decoder = new BASE64Decoder();
            // Base64 解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {
                    // 调整异样数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {System.out.println(e);
        }
        return false;
    }
    private static boolean isEmpty(String input) {return input == null || "".equals(input);
    }

运行后果:


图片上传云存储,返回 url

将图片上传至云存储,返回图片的 url

/**
     * 上传图片到云存储,返回 url 和图片名称
     * @param multipartFile
     * @return
     */
    @Override
    public BaseResponse<Map<String, String>> upload(MultipartFile multipartFile) {BaseResponse baseResponse = new BaseResponse();

        try {byte[] picBbytes= multipartFile.getBytes();
            String base64Str=new String(org.apache.commons.codec.binary.Base64.encodeBase64(picBbytes),"utf-8");
            String picUrl=getUploadPicUrl(base64Str);
            Map<String, String> map = new HashMap<>();
            if (picUrl != null){map.put("picUrl", picUrl);
                map.put("picName", multipartFile.getOriginalFilename());
                baseResponse.setData(map);
                baseResponse.setMsg("图片上传胜利");
                baseResponse.setCode("0");
                return baseResponse;
            }
        }catch (IOException e) {logger.error("错误码:{}, 错误信息:{},record:{}", DefaultErrorCode.PIC_UPLOAD_ERROR.getCode(), DefaultErrorCode.PIC_UPLOAD_ERROR.getMessage(), e);
        }
        baseResponse.setMsg(DefaultErrorCode.PIC_UPLOAD_ERROR.getMessage());
        baseResponse.setCode("-1");
        return baseResponse;
    }
    /**
     * 图片存储到云存储
     * @param picBase64
     * @return
     */
    public String getUploadPicUrl(String picBase64) {
        try{picBase64 = picBase64.replaceFirst("data:image/jpg;base64,", "");
            byte[] picBuff = Base64.decode(picBase64);
            HikCStorConstant cStorConstant = getStorageDeviceList();
            //logger.debug("获取存储设备信息列表:" + cStorConstant.getDeviceIP());
            if(cStorConstant != null){if (poolInfo == null){poolInfo = getPoolInfoList(cStorConstant.getDeviceID());
                }
                //logger.debug("获取资源池:" + poolInfo);
                if(poolInfo != null){//logger.debug("图片筹备上传云存储");
                    cStorConstant.setPoolId(poolInfo.getPoolId());
                    cStorConstant.setSerialID(cStorConstant.getDeviceID());
                    String secretKey = new String(AESSO.decrypt(java.util.Base64.getDecoder().decode(cStorConstant.getSecretKey()), Authentication.exportSK(),false),"UTF-8");
                    //logger.debug("图片上传云存储 secretKey:" + secretKey);
                    cStorConstant.setSecretKey(secretKey.trim());

                    String picUrl = hikCStorUtil.writePic(cStorConstant,picBuff);
                    logger.debug("图片上传云存储 URL:"+picUrl);
                    return "http://" + cStorConstant.getDeviceIP() + ":" + String.valueOf(cStorConstant.getPicDownloadPort()) + picUrl;
                }
            }
        }catch (Exception e){logger.error("getUploadPicUrl error:",e);
        }
        return null;
    }
    /** 获取服务信息 */
    public ServiceAddressInfoDto findServiceInfo() {
        ServiceAddressInfoDto serviceAddressInfoDto = null;
        try {ApiResponse<ServiceInfoDto> serviceInfo = serviceDirectoryClient.getServiceInfo("sac","sac");
            if (serviceInfo.getCode().equals("0")){if (!org.apache.commons.lang3.ObjectUtils.isEmpty(serviceInfo.getData()) && serviceInfo.getData().getAddress().size() > 0){for (ServiceAddressInfoDto dto:serviceInfo.getData().getAddress()) {if (dto.getNetprotocol().toLowerCase().equals("http")){
                            serviceAddressInfoDto = dto;
                            break;
                        }
                    }
                    serviceAddressInfoDto=serviceInfo.getData().getAddress().get(0);
                    if (serviceAddressInfoDto == null){serviceAddressInfoDto = serviceInfo.getData().getAddress().get(0);
                    }
                }
            }
        } catch (Exception e) {logger.error("findServiceInfo error:",e);
        }
        return serviceAddressInfoDto;
    }
    /**
     * 获取存储设备信息列表
     * @return
     * @throws Exception
     */
    public HikCStorConstant getStorageDeviceList() throws Exception {
        String uri = "/ISAPI/Storage/storageDeviceList?marker=&maxKeys=3000";
        ServiceAddressInfoDto dto=findServiceInfo();
        String url = null;
        if (dto!=null) {String sacUrl = "http://" + dto.getIp() + ":" + dto.getPort();
            url = sacUrl + uri;
        }
        String secretKey = new String(Authentication.exportSK(),"UTF-8");
        String accessKey = new String(Authentication.exportAK(),"UTF-8");

        String date = DateGMCUtil.getGmtTime();

        String auth = AuthProcess.getAuthorization(accessKey, secretKey, "GET", "","", date, uri, 1,"storage");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Date", date);
        httpHeaders.set("Authorization", auth);
        httpHeaders.set("Connection", "close");
        httpHeaders.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));

        HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity<String> entity = myRestTemplates.exchange(URI.create(url), HttpMethod.GET, httpEntity, String.class);
        if(entity != null && entity.getStatusCode() == HttpStatus.OK){ResourceDeviceInfo deviceInfo = JSONObject.parseObject(entity.getBody(),ResourceDeviceInfo.class);
            for(HikCStorConstant cStorConstant : deviceInfo.getList()){
                /**deviceType:1- 云存储,2-CVR,3-PCNVR2.0,4-NVR*/
                if(cStorConstant.getPicDownloadPort()!= 0 && cStorConstant.getPicUploadPort() != 0 /*&& cStorConstant.getDeviceType() == 1 */){return cStorConstant;}
            }
        }
        return null;
    }
    /**
     * 获取资源池
     * @return
     * @throws Exception
     */
    public PoolInfo getPoolInfoList(String deviceId) throws Exception {
        String uri = "/ISAPI/Storage/poolInfoList?marker=&maxKeys=3000";
        ServiceAddressInfoDto dto=findServiceInfo();
        String url = null;
        if (dto!=null) {String sacUrl = "http://" + dto.getIp() + ":" + dto.getPort();
            url = sacUrl + uri;
        }

        String secretKey = new String(Authentication.exportSK(),"UTF-8");
        String accessKey = new String(Authentication.exportAK(),"UTF-8");

        String date = DateGMCUtil.getGmtTime();

        String auth = AuthProcess.getAuthorization(accessKey, secretKey, "GET", "","", date, uri, 1,"storage");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Date", date);
        httpHeaders.set("Authorization", auth);
        httpHeaders.set("X-Stor-DeviceID", deviceId);
        httpHeaders.set("Connection", "close");

        httpHeaders.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));

        HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
        RestTemplate myRestTemplate=new RestTemplate();
        ResponseEntity<String> entity = myRestTemplate.exchange(URI.create(url), HttpMethod.GET, httpEntity, String.class);
        if(entity.getStatusCode() == HttpStatus.OK){ResourcePoolInfo poolInfo = JSONObject.parseObject(entity.getBody(),ResourcePoolInfo.class);
            Boolean isExist = false;
            for(PoolInfo pool : poolInfo.getList()){
                //0- 通用池 1- 视频池 3- 图片池
                if(pool.getPoolType() == 0  && pool.getPoolStatus() == 1){
                    // 是否存在图片资源池
                    isExist = true;
                    return pool;
                }
            }
            if (!isExist){for(PoolInfo pool : poolInfo.getList()){
                    //0- 通用池 1- 视频池 3- 图片池
                    if(pool.getCoverType()==0 && pool.getPoolType() == 0 && "1".equals(pool.getDeviceType()) && pool.getPoolStatus() == 1){
                        // 不可笼罩通用资源池
                        return pool;
                    }
                }
            }
        }
        return null;
    }

测试:

退出移动版