0
I need to download an image and record it on the device.
I download it and record in one InputSstream
InputStream imagem = comunicacao.getWSStream(servico, nome);
But when it comes to converting it, the decodebyteArray ends up generating a null.
private void gravaImagem(InputStream imagem, String nome){
try {
FileOutputStream escrita = new FileOutputStream(new File(SivaPlusConfig.DIRETORIO_SDIMG + nome));
byte[] bytes = readBytes(imagem);
Bitmap imagem2 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); // gera null
if (imagem2 == null) {
return;
}
imagem2.compress(Bitmap.CompressFormat.PNG, 90, escrita);
escrita.flush();
escrita.close();
imagem.close();
} catch (Exception e){
LogUtil.writeFile((Activity) mContext, "Erro ao gravar imagem: " + nome);
}
}
private byte[] readBytes(InputStream in) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
byte[] bytes = bos.toByteArray();
return bytes;
} finally {
bos.close();
}
}
Sorry for the formatting of the text. I’m still adapting and learning about the community.
You could simply use the Glide or Picasso libraries that already do almost all this with a few lines of code.
– Márcio Oliveira
@Márciooliveira thanks for the reply but I do not want to use third party library.
– Gabriel
Well, how about some security clearances first to analyze the problem. Before using the byte variable, it is advisable to control that null and bytes.length >0 are not found in the write method. Only with the code shown, the problem can originate from multiple instructions, even in SD card access permissions and/or validate that it exists. Suggested to add the suggestions I provided to more precisely locate the problem.
– Pedro Ferreira
@Gabriel, okay, I just suggested it because they’re classic and widely used libraries (including some of Google’s own apps) that do a great job.
– Márcio Oliveira
@Márciooliveira clear, I understand. But it is a little more complicated to be able to use these libraries where I work.
– Gabriel
@Pedroferreira understand but the strange thing is that I receive all the data. Both Inputstream and bytes are populated but when using the decodeByteArray method generates null for imagem2
– Gabriel
Null in decodeByte or compress? What are you trying to do in compress is not possible without making a bitmap copy to be mutable
– Pedro Ferreira