2

Olá, estou salvando imagens no banco de dados. Mas a resolução está muito ruim. Estou usando o seguinte:

btncamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tirarfoto();

        }
    });

    btngaleria.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galeriaIntent = new Intent(Intent.ACTION_GET_CONTENT);
            galeriaIntent.setType("image/*");

            startActivityForResult(galeriaIntent, ESCOLHERFOTO);


        }
    });

Em outro trecho uso isso:

 if (foto != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    foto.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte[] bytearray = stream.toByteArray();

                    final ParseFile fileimagem = new ParseFile("imagem.jpg", bytearray);
                    fileimagem.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {

                            if (e == null) {
                                salvarDica(fileimagem);


                            }
                        }
                    });
                } else {
                    salvarDica(null);
                }

E tenho também esses métodos:

private void tirarfoto() {
    Intent abrircamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    if (abrircamera.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(abrircamera, TIRARFOTO);
    }
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ESCOLHERFOTO && resultCode == RESULT_OK) {

        uricaminhodafoto = data.getData();
        try {
            foto = MediaStore.Images.Media.getBitmap(getContentResolver(), uricaminhodafoto);
            foto = Bitmap.createScaledBitmap(foto, 200, 200, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        picture.setImageBitmap(foto);


    }


    if (requestCode == TIRARFOTO && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        foto = (Bitmap) extras.get("data");
        picture.setImageBitmap(foto);


    }
}

Parte da minha configuração:

 <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/picture"
            android:src="@drawable/picture"
            android:layout_gravity="center_horizontal"
            android:scaleType="centerCrop"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

A resolução da imagem salva é terrível. Alguém sabe como resolver? Obrigada.

1

2 Respostas 2

2

Tente substituir isso:

foto = Bitmap.createScaledBitmap(foto, 200, 200, false);

Por isso:

foto = Bitmap.createScaledBitmap(foto, 1000, 1000, false);

Outra alternativa é apenas remover essa linha e deixar de realizar redimensionamento do Bitmap.

5
  • Mas até quando é foto e não passa por esta redução está horrível 29/11/2016 às 13:26
  • @ElaineBredaSchwaner Bem, então eu não sei. Se conseguir achar a solução postarei outra resposta. 29/11/2016 às 13:51
  • Olá está dando certo para salvar imagens que vem da Galeria. Muito obrigada! A câmera não foi utilizar, já que não deu certo. 29/11/2016 às 17:22
  • Gostaria de saber se há uma maneira de salvar com um número de KB definido. 29/11/2016 às 17:22
  • @ElaineBredaSchwaner É difícil saber-se o tamanho que a imagem ocupará antes de gerá-la, vez que os algoritmos de compressão de imagens tem características que conseguem comprimir melhor algumas imagens do que outras, variando de acordo com as cores e texturas presentes na imagem. Entretanto, a rigor você poderia ou reduzir o tamanho da imagem (que são esses dois parâmetros) ou reduzir o número correspondente a qualidade no foto.compress(Bitmap.CompressFormat.JPEG, 100, stream);. 29/11/2016 às 18:42
0

Bom, pessoal, muito obrigada a quem colaborou. Fui juntando todas e achei uma solução boa para mim. Não consegui a resolução da foto tirada da câmera ficar boa mesmo, então deixei só vir da galeria. Mas para meu App, já basta. Agora o que faz a foto diminuir bastante o tamanho (ficar no tamanho exato do meu ImageView) sem perder a definição e ficar bem leve para ser carregada e para o usuário salvar no banco foi isto:

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ESCOLHERFOTO && resultCode == RESULT_OK) {

        uricaminhodafoto = data.getData();
        try {
            foto = MediaStore.Images.Media.getBitmap(getContentResolver(), uricaminhodafoto);


            foto2 = getResizedBitmap(foto);
        } catch (IOException e) {
            e.printStackTrace();
        }

        picture.setImageBitmap(foto2);


    }



}

public Bitmap getResizedBitmap(Bitmap foto) {
    int width = foto.getWidth();
    int height = foto.getHeight();
    if (height > width) {


        newHeight = 400;
        newWidth = (width * 400) / height;
    }
    if (height == width) {

        newHeight = 240;
        newWidth = 240;
    }


    if (width > height) {

        newWidth = 760;
        newHeight = (height * 760 / width);
    }

    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(
            foto, 0, 0, width, height, matrix, false);
    foto.recycle();

    return resizedBitmap;
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .