Now we'll look at the case where we take a picture with the camera using the 'How to Program the Android Camera to Take Pictures' tutorial. When we take a picture, we receive a byte array... what do we do with this? How can we convert this to a image in our SD card? Let's do it.
We create a File object with the place where to store the images.
File sdImageMainDirectory = "/sdcard/myImages";
We initialize some variables.
FileOutputStream fileOutputStream = null;
The image file name
String nameFile = “myImage”
Now, the quality of the image. This is a value between 0 and 100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting (via Google Android Reference)
int quality = 50;
We create the options we are going to use in our compression (adding the sample size)
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 5;
We create the Bitmap from the imageData (byte array) and we throw it to the FileOutputStream with the name and the compression given (In this case JPEG)
Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,imageData.length,options);
fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
myImage.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
At this point, we will have the image stored in our SD card. Here we can play with the quality and sample values. How will the image look like with different values? You can try...
This is the core functionality, but the full source code can be found in my Code Snippets.