Converting Inputstream to Image

Asked

Viewed 80 times

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.

  • 1

    You could simply use the Glide or Picasso libraries that already do almost all this with a few lines of code.

  • @Márciooliveira thanks for the reply but I do not want to use third party library.

  • 1

    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.

  • 1

    @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árciooliveira clear, I understand. But it is a little more complicated to be able to use these libraries where I work.

  • @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

  • 1

    Null in decodeByte or compress? What are you trying to do in compress is not possible without making a bitmap copy to be mutable

Show 2 more comments

1 answer

0


Finished. It was problem in webservice, "Content-Type" was different than expected. Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.