Android – compress the bitmap and save it to the activity result of the sdcard
I've been discussing this problem and I'm not sure what to do. What I want to do is: take a picture, compress it to PNG (keep the original size), and then save it to sdcard. The reason why I need to do this is because I have to re compress it again, and then encode it in Base64, So that I can send it to the server. The problem is 1. The file is too large. 2. I don't have enough memory. 3. I'm not sure if I can perform this operation correctly
Thanks for your help
This is my code:
@Override
public void onClick(View button) {
switch (button.getId()) {
case R.id.cameraButton:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File("/sdcard/test.png")));
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
break;
case R.id.galleryButton:
sendToDatabase();
break;
}
}
// Camera on activity for result - save it as a bmp and place in imageview
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
}
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "result ok");
picture = BitmapFactory.decodeFile("/sdcard/test.png");
// Create string to place it in sd card
String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
//create output stream
OutputStream outputStream = null;
//create file
File file = new File(extStorageDirectory, "test.png");
try {
outputStream = new FileOutputStream(file);
picture.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
//picture.recycle();
outputStream.flush();
outputStream.close();
} catch (IOException e){
Log.d(TAG, "ERROR");
}
imageView.setImageBitmap(picture);
}
}
public void sendToDatabase() {
InputStream inputStream = null;
//get the picture from location
picture = BitmapFactory.decodeFile("/sdcard/test.png");
// CONVERT:
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Boolean didItWork = picture.compress(Bitmap.CompressFormat.PNG, 50, outStream);
picture.recycle();
if (didItWork = true) {
Log.d(TAG, "compression worked");
}
Log.d(TAG, "AFTER. Height: " + picture.getHeight() + " Width: "
+ picture.getWidth());
final byte[] ba = outStream.toByteArray();
try {
outStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
resolvent:
When you do picture. Compress (bitmap. Compressformat. PNG, 50, outstream); Compression cannot work as lossless PNG, and the quality setting will be ignored. Therefore, parameter 50 does not work in this case. So I suggest you change compressformat.png to compressformat.jpeg