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

来源:互联网 发布:html5手机网站源码 编辑:程序博客网 时间:2024/05/22 00:48

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

一.图片加密

传入图片地址即可

public static String imageBase64(String path) {        InputStream in = null;        ByteArrayOutputStream byteArrOps = null;        int length = -1;        byte[] buffer = new byte[1024 * 2];        byte[] data = null;        // 加密        BASE64Encoder encoder = new BASE64Encoder();        try {            URL url = new URL(path);            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();            urlConnection.setRequestMethod("GET");            urlConnection.setReadTimeout(1000 * 10);            if (urlConnection.getResponseCode() == 200) {                in = urlConnection.getInputStream();                byteArrOps = new ByteArrayOutputStream();                while ((length = in.read(buffer)) != -1) {                    byteArrOps.write(buffer, 0, length);                }                //总大小                int totalSize = urlConnection.getContentLength();                byteArrOps.flush();                data = byteArrOps.toByteArray();                // 下载大小: data.length            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (byteArrOps != null) {                    byteArrOps.close();                }                if (in != null) {                    in.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }        return encoder.encode(data);    }

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

public static boolean generateImage(String imgStr, String path) {        if (imgStr == null)            return false;        BASE64Decoder decoder = new BASE64Decoder();        try {            // 解密            byte[] b = decoder.decodeBuffer(imgStr);            // 处理数据            for (int i = 0; i < b.length; ++i) {                if (b[i] < 0) {                    b[i] += 256;                }            }            OutputStream out = new FileOutputStream(path);            out.write(b);            out.flush();            out.close();            return true;        } catch (Exception e) {            return false;        }    }

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

public static void main(String[] args){        String imgPath = "阿里云图片路径";        String str = imageBase64(imgPath);        boolean b = generateImage(str, "D:\\2.jpg");        System.out.println(b);    }
原创粉丝点击