gpt4 book ai didi

java - 转换为 base64 并在结果中重复?

转载 作者:行者123 更新时间:2023-11-30 00:26:41 24 4
gpt4 key购买 nike

我在 android 中获取 url 并使用此代码将数据流转换为 64 位数据字符串:

URL url = new URL("http://iranassistance.com/images/sos-logo.png");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename="downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();byte[] imageBytes = new byte[urlConnection.getContentLength()];
inputStream.read(imageBytes, 0, imageBytes.length);
inputStream.close();
String base64Image = Base64.encodeToString(imageBytes, Base64.DEFAULT);

但是 base64Image 结果不完整,给出了这样的东西:

......nUTJaJnb7PLyscfBMQLLiexyKSEh/o2RfctcZtc8Hr5xcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA........

重复的“A”显示有问题,图像不完整!为什么这不能正常工作?

最佳答案

简单:

inputStream.read(imageBytes, 0, imageBytes.length);

您假设上述总是一次性读取所有字节。

错了。此方法读取它想要读取的字节数。因此它返回给您读取的 字节。查看其 javadoc :

Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

换句话说:你必须循环并累积这些数字,直到你得到你正在寻找的字节数!

然后您得到了那些 A 字符:您的数组最初全为 0。如前所述:您只填充了该数组的部分。所以数组的其余部分仍然是 0 - 编码后结果为 AAAAA。

关于java - 转换为 base64 并在结果中重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com