How Do I compress Size of Image - java

Here is the code which i am using to capture image, but now my question is How Do I Compress Size of Image taken by my Custom Camera
CameraSurfaceView.java:
class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
Camera camera;
CameraSurfaceView(Context context) {
super(context);
SurfaceHolder holder = this.getHolder();
holder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
camera.setDisplayOrientation(90);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
}
public void takePicture(PictureCallback imageCallback) {
Camera.Parameters params = camera.getParameters();
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, imageCallback);
}
}
Here is the Class which I am using to Capture Image
CameraCaptureActivity.java:
CameraSurfaceView cameraSurfaceView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_capture);
// set up our preview surface
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
cameraSurfaceView = new CameraSurfaceView(this);
preview.addView(cameraSurfaceView);
// grab out shutter button so we can reference it later
shutterButton = (Button) findViewById(R.id.btnCapture);
shutterButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
takePicture();
}
private void takePicture() {
shutterButton.setEnabled(false);
cameraSurfaceView.takePicture(this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO something with the image data
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
strDateFormat = simpleDateFormat.format(new Date());
String photoFile = strRecordName+strDateFormat+".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(CameraCaptureActivity.this, "Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
// Restart the preview and re-enable the shutter button so that we can take another picture
camera.stopPreview();
shutterButton.setEnabled(false);
} catch (Exception error) {
Toast.makeText(CameraCaptureActivity.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CustomCamera");
}
public void onResume()
{
super.onResume();
shutterButton.setEnabled(true);
}

Do like
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap pic = BitmapFactory.decodeByteArray(data, 0, data.length);
//Rotate the image by 90 degrees before we save it
Matrix matrix = new Matrix();
matrix.postRotate(90);
pic = Bitmap.createBitmap(pic , 0, 0, pic.getWidth(), pic.getHeight(), matrix, true);
........
FileOutputStream fos = new FileOutputStream(pictureFile);
pic.compress(Bitmap.CompressFormat.PNG, 90, fOut);
}

Related

Android App: Displaying a Bitmap image in an ImageView

I'm making an application that implements the Camera, and I was wondering why does the image get saved to a tiny bitmap when I take a picture?
When I press the capture button, for some reason the image gets scaled down (I need to save the image to INTERNAL memory, not external/sd card) and I end up having to scale it back up to display it in the ImageView, which obviously makes the photo a little bit more grainy than the camera preview is. Is there a better way to do this?
I want it to be similar to SnapChat, where the picture you take is displayed exactly how it looked when you took it...
Here's the main Activity:
public class MainActivity extends FragmentActivity {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
private Camera mCamera;
private CameraPreview mPreview;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
if(checkCameraHardware(mContext)){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
FileOutputStream fos = openFileOutput("img.jpg", Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return "img.jpg";
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
Intent intent = new Intent(mContext, ImageDisplayActivity.class);
intent.putExtra(ImageDisplayActivity.KEY_PATH, "img.jpg");
startActivity(intent);
}
}
}.execute();
}
};
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Create a File for saving an image or video */
}
And here's the Image Display Activity:
public class ImageDisplayActivity extends FragmentActivity {
public static final String KEY_PATH = "img.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
Intent intent = getIntent();
String path = getIntent().getStringExtra(ImageDisplayActivity.KEY_PATH);
try {
java.io.FileInputStream in = this.openFileInput(path);
Bitmap bitmap = BitmapFactory.decodeStream(in);
ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);
touch = arrangeImageView(touch);
touch.setImageBitmap(bitmap);
in.close();
Canvas c = new Canvas(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
private ZoomInZoomOut arrangeImageView(ZoomInZoomOut img){
try {
img.setRotation(90);
img.setScaleX(2f);
img.setScaleY(2f);
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
}

Capture image in portrait but get an ouput of landscape in directory

I am making my own camera in android, then whenever I capture images the images orientation is okay. but when i open it in my external sdcard file it is like that:
this is my code:
public class CameraApp extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "IMG_";
private static final String IMAGE_FOLDER = "/PhoneController/";
private static final String EXTENTION = ".jpg";
private String pictureName = "";
public String picNameToshare = "";
static final int FOTO_MODE = 0;
String speed;
String imageFilePath;
private Handler mHandler = new Handler();
public static String imageFilePath1;
FileOutputStream fos = null;
public Bitmap framebmpScaled;
public Bitmap SelecedFrmae;
public static Bitmap mergeBitmap;
public static Bitmap bmpfULL;
Camera camera;
Button button;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.camera);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
Handler myHandler = new Handler();
if (previewing) {
camera.stopPreview();
previewing = false;
Log.e("", "one");
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
myHandler.postDelayed(mMyRunnable, 2000); // called after 5
// seconds
button.setText("Waiting...");
Log.e("", "two");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Handler myHandler = new Handler();
* myHandler.postDelayed(mMyRunnable, 5000); // called after 5
* seconds button.setText("Waiting...");
*/
}
};
private Runnable mMyRunnable = new Runnable() {
public void run() {
Camera.Parameters params = camera.getParameters();
params.set("rotation", 90);
camera.setParameters(params);
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
storePicture(mergeBitmap);
button.setText("Capture");
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Display display = getWindowManager().getDefaultDisplay();
final int ScreenWidth = display.getWidth();
final int ScreenHeight = display.getHeight();
Log.e("" + display.getWidth(), "" + display.getWidth());
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap bmpScaled1 = Bitmap.createScaledBitmap(bitmapPicture,
ScreenWidth, ScreenHeight, true);
mergeBitmap = bmpScaled1;
showPicture();
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setDisplayOrientation(90);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
void storePicture(Bitmap bm) {
mHandler.post(new Runnable() {
public void run() {
// showPicture();
}
});
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
this.pictureName = TAG + timeStamp;
picNameToshare = this.pictureName;
this.imageFilePath = IMAGE_FOLDER + this.pictureName + EXTENTION;
this.imageFilePath = sanitizePath(this.imageFilePath);
try {
checkSDCard(this.imageFilePath);
fos = new FileOutputStream(this.imageFilePath);
if (fos != null) {
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
fos.close();
}
} catch (IOException ioe) {
Log.e(TAG, "CapturePicture : " + ioe.toString());
} catch (Exception e) {
Log.e(TAG, "CapturePicture : " + e.toString());
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
imageFilePath1 = this.imageFilePath;
}
/**
* Check the SDCard is mounted on device
*
* #param path
* of image file
* #throws IOException
*/
void checkSDCard(String path) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Toast.makeText(this,
"Please insert sdcard other wise image won't stored",
Toast.LENGTH_SHORT).show();
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording is exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
please help me.
Try using this
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);

Android save image taken with flash on (Nexus 4)

Below is the code for a custom camera app I'm working on. Everthing works fine, except when the images are taken with flash on. With flash on, the preview showed to the user to accept the image looks right, but the image saved to the sdcard is very dark (with only white objects slightly visible) and often just black. I've been trying to figure out the problem for days now. Any ideas what might be going on?
public class CustomCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
Surfaceview surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
...
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
Camera.Parameters parameters = camera.getParameters();
camera.setDisplayOrientation(90);
determineDisplayOrientation();
camera.setPreviewDisplay(surfaceHolder);
previewing = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
List<String> supportedFocusModes = parameters.getSupportedFocusModes();
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
}
if (parameters.getSupportedWhiteBalance().contains(
Parameters.WHITE_BALANCE_AUTO)) {
parameters.setWhiteBalance(Parameters.WHITE_BALANCE_AUTO);
}
if (parameters.getSupportedSceneModes().contains(
Parameters.SCENE_MODE_AUTO)) {
parameters.setSceneMode(Parameters.SCENE_MODE_AUTO);
}
camera.setParameters(parameters);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
flashButton.setBackgroundResource(R.drawable.auto_flash);
camera = Camera.open(CURRENT_CAMERA_ID);
Camera.Parameters camParameters = camera.getParameters();
flashSupported = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if ( flashSupported){
camParameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
lastFlashMode = AUTO_FLASH;
camera.setParameters(camParameters);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
//click listener for button to take picture
public void takePicture(View view){
if (camera != null){
orientationListener.rememberOrientation();
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
showPicPreviewScreen();
}
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback() {
#Override
public void onShutter() {
}
};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}
};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
int rotation = (displayOrientation + orientationListener.getRememberedOrientation() + layoutOrientation) % 360;
if (rotation != 0){
Log.e("rotaion", "not 0, rotating");
Bitmap oldBitmap = bitmapPicture;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmapPicture = Bitmap.createBitmap(bitmapPicture, 0, 0, bitmapPicture.getWidth(), bitmapPicture.getHeight(), matrix, false);
oldBitmap.recycle();
}
camera.stopPreview();
previewing = false;
ImageSaver imageSaver = new ImageSaver();
imageSaver.saveImage(getApplicationContext(), bitmapPicture);
}
};
}
And here's the class that saves the image
public class ImageSaver{
private Context context;
private String NameOfFolder = "/ProjectFolder";
String fileName;
String file_path;
public void saveImage(Context context,Bitmap ImageToSave){
context = context;
file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+ NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
File dir = new File(file_path);
if(!dir.exists()){
dir.mkdirs();
}
fileName = CurrentDateAndTime+ ".jpg";
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
ImageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fOut); //85
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {UnableToSave();}
catch (IOException e){UnableToSave();}
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
}
Thanks a lot!

How can i capture image with a touch on surface view

public class AndroidCamera extends Activity implements OnTouchListener, SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
EditText txtData, Info,Age;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.capturepreview);
txtData = (EditText) findViewById(R.id.editText1);
Info = (EditText) findViewById(R.id.Name);
Info.setHint("enter name");
Age = (EditText) findViewById(R.id.Age);
Age.setHint("Age");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
// onTouchEvent(null);
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Asw");
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v)
{
if(!previewing)
{
camera = Camera.open(0);
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e)
{
e.printStackTrace();
}
}else txtData.setText("null");
}
}});
buttonCapturePreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
captureImage();
}
private void captureImage()
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
if(camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}});
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_camera, menu);
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
return super.onTouchEvent(event);
//return false;
}
I have used a button to capture the image. Now i wanted to capture and save the image with just a touch on surface view. I wrote some code.Its not showing any error but it is not working also. Could you please tell me where i am going wrong. Please help
Try this to take screen shot programmatically...
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SnapShot extends Activity implements OnClickListener,
SurfaceHolder.Callback, Camera.PictureCallback {
SurfaceView cameraView;
SurfaceHolder surfaceHolder;
Camera camera;
LayoutInflater inflater;
Uri imageFileUri;
Button save;
Button retry;
View viewControl;
LayoutParams layoutParamsControl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_camera);
cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
surfaceHolder = cameraView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
cameraView.setFocusable(true);
cameraView.setFocusableInTouchMode(true);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
inflater = LayoutInflater.from(getBaseContext());
viewControl = inflater.inflate(R.layout.camera_control, null);
save = (Button) viewControl.findViewById(R.id.vc_btn_keep);
retry = (Button)viewControl.findViewById(R.id.vc_btn_discard);
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
// parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
// parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
Log.v("surfaceCreated", exception.getMessage());
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
this.addContentView(viewControl, layoutParamsControl);
save.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
insertImage(data);
Intent i = new Intent();
i.putExtra("data", imageFileUri.toString());
setResult(-1, i);
finish();
}});
retry.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
public void insertImage(byte[] data)
{
Bitmap b = null;
try {
b = GeneralUtils.decodeFile(data, this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//b = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
Matrix m = new Matrix();
if (b.getWidth() > b.getHeight())
{
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
b.recycle();
data = null;
b = null;
m = null;
imageFileUri = Uri.parse(result);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, this);
}
}

How to save overlay with camera preview in android?

I am able to place a overlay over a live camera feed, but I also need to save the image captured by camera with that overlay.
Here is the code of my MainActivity.class file :
public class MainActivity extends Activity {
private Button takePhoto, pickPhoto;
private FrameLayout preview;
private CameraSurfaceView cameraSurfaceView;
private static final int SELECT_PICTURE_ACTIVITY_RESULT_CODE = 1;
private static final int CAMERA_PIC_REQUEST = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.btn_takephoto);
pickPhoto = (Button) findViewById(R.id.btn_pickPhoto);
preview = (FrameLayout) findViewById(R.id.frameLayout1);
takePhoto.setOnClickListener(clickListener);
pickPhoto.setOnClickListener(clickListener);
cameraSurfaceView = new CameraSurfaceView(MainActivity.this);
preview.addView(cameraSurfaceView);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(takePhoto)) {
Camera camera = cameraSurfaceView.getCamera();
camera.takePicture(null, null, new HandlePictureStorage());
} else if (v.equals(pickPhoto)) {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*"); // to pick only images
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent,
SELECT_PICTURE_ACTIVITY_RESULT_CODE);
}
}
};
private class HandlePictureStorage implements PictureCallback {
#Override
public void onPictureTaken(byte[] picture, Camera camera) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "CameraTest" + date + ".jpg";
String filename = Environment.getExternalStorageDirectory()
+ File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(picture);
fos.close();
Toast.makeText(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d("Error",
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
Intent newInt = new Intent(MainActivity.this, AddImageOverlay.class);
newInt.putExtra(Constant.BitmatpByteArray, filename);
startActivity(newInt);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_RESULT_CODE:
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Photo Picked",
Toast.LENGTH_SHORT).show();
// deal with it
break;
default:
// deal with it
break;
}
}
}
}
And the code of CameraSurfaceView.java :
public class CameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
public CameraSurfaceView(Context context) {
super(context);
// Initiate the Surface Holder properly
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder h, int format, int width,
int height) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
h.getSurface().setLayer(R.drawable.ic_launcher);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(this.holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when replaced with a new screen
// Always make sure to release the Camera instance
camera.stopPreview();
camera.release();
camera = null;
}
public Camera getCamera() {
return this.camera;
}
}

Categories