java读取远程图片缺失或者不全

本文介绍了一种确保从网络上完整加载图片的方法。通过使用getContentLength()方法获取远程资源的长度,并循环读取直到全部数据被加载,可以有效避免图片加载不完全的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考博客:https://blog.csdn.net/changerzhuo_319/article/details/70161387
读取远程图片时,读不全,图片只读到一部分,怎么回事呢?
这就是网络上读取时丢包了。
怎么样才能读取完整的图片呢?
其实很简单,控制好读完才停止。怎么确定读完了呢。连接有个方法获取远程资源的长度–getContentLength()
具体代码如下:

public static String urlToString(String imgUrl){
        byte[] result=null;
        InputStream inStream=null;
        String photo = "";
        try {
            //创建URL
            URL url=new URL(imgUrl);
            //创建连接
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5*1000);
            inStream=conn.getInputStream();
            int count=conn.getContentLength();//获取远程资源长度
            result=new byte[count];
            int readCount=0;
            while(readCount<count){//循环读取数据
                readCount+=inStream.read(result,readCount,count-readCount);
            }
            photo = toBase64(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取远程图片失败", e);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                log.error("文件处理错误!", e);
            }
            log.info("o==||=====>读取图片返回");
        }
        return photo;
    }
    private static String toBase64(byte[] imgData) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(imgData);
    }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值