读取阿里云服务器图片到本地

港控/mmm° 2022-06-04 00:18 364阅读 0赞

摘要:根据阿里云服务器图片路径,读取保存到本地,分2步,先是把图片加密成
字符串,在通过解密这字符串保存在本地磁盘

一.图片加密

传入图片地址即可

  1. public static String imageBase64(String path) {
  2. InputStream in = null;
  3. ByteArrayOutputStream byteArrOps = null;
  4. int length = -1;
  5. byte[] buffer = new byte[1024 * 2];
  6. byte[] data = null;
  7. // 加密
  8. BASE64Encoder encoder = new BASE64Encoder();
  9. try {
  10. URL url = new URL(path);
  11. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  12. urlConnection.setRequestMethod("GET");
  13. urlConnection.setReadTimeout(1000 * 10);
  14. if (urlConnection.getResponseCode() == 200) {
  15. in = urlConnection.getInputStream();
  16. byteArrOps = new ByteArrayOutputStream();
  17. while ((length = in.read(buffer)) != -1) {
  18. byteArrOps.write(buffer, 0, length);
  19. }
  20. //总大小
  21. int totalSize = urlConnection.getContentLength();
  22. byteArrOps.flush();
  23. data = byteArrOps.toByteArray();
  24. // 下载大小: data.length
  25. }
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. } finally {
  29. try {
  30. if (byteArrOps != null) {
  31. byteArrOps.close();
  32. }
  33. if (in != null) {
  34. in.close();
  35. }
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. return encoder.encode(data);
  41. }

二.图片解密
第一个参数是图片的加密字符串,第二个参数是你保存本地的路径,后面加一个图片的名即可

  1. public static boolean generateImage(String imgStr, String path) {
  2. if (imgStr == null)
  3. return false;
  4. BASE64Decoder decoder = new BASE64Decoder();
  5. try {
  6. // 解密
  7. byte[] b = decoder.decodeBuffer(imgStr);
  8. // 处理数据
  9. for (int i = 0; i < b.length; ++i) {
  10. if (b[i] < 0) {
  11. b[i] += 256;
  12. }
  13. }
  14. OutputStream out = new FileOutputStream(path);
  15. out.write(b);
  16. out.flush();
  17. out.close();
  18. return true;
  19. } catch (Exception e) {
  20. return false;
  21. }
  22. }

三.测试
我这里图片取名为2.jpg

  1. public static void main(String[] args){
  2. String imgPath = "阿里云图片路径";
  3. String str = imageBase64(imgPath);
  4. boolean b = generateImage(str, "D:\\2.jpg");
  5. System.out.println(b);
  6. }

发表评论

表情:
评论列表 (有 0 条评论,364人围观)

还没有评论,来说两句吧...

相关阅读