How can i capture image with a touch on surface view - java

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);
}
}

Related

How Do I compress Size of Image

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);
}

Values is not updated after asynchronous task execution in android

This is my code in DashBoard_Gujrat Activity
public class DashBoard_Gujrat extends NavigationDrawerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater
.inflate(R.layout.dashboard_new, null, false);
mDrawerLayout.addView(contentView, 0);
bar = getActionBar();
bar.setDisplayShowHomeEnabled(true);
try {
dbhelper = new DatabaseHelper(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bar.setBackgroundDrawable(getResources().getDrawable(
R.drawable.top_header));
yesarrow = (ImageView) findViewById(R.id.yes_arrow);
yes_vehicle = (ImageView) findViewById(R.id.yes_vehicle);
ostwald_bold = Typeface.createFromAsset(getAssets(),
"fonts/Oswald-Bold.otf");
ostwald_regular = Typeface.createFromAsset(getAssets(),
"fonts/Oswald-Regular.otf");
roboto_light = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
roboto_regular = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Regular.ttf");
roboto_thin = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Thin.ttf");
viewPager = (ViewPager) findViewById(R.id.summarypager);
Ylayout = (LinearLayout) findViewById(R.id.yesLayout);
Yclick = (LinearLayout) findViewById(R.id.yLayout);
Tclick = (LinearLayout) findViewById(R.id.tLayout);
Tlayout = (LinearLayout) findViewById(R.id.toLayout);
first = (ImageView) findViewById(R.id.firstimage);
arrowtrip = (ImageView) findViewById(R.id.ontrip_arrow);
valve6 = (ImageView) findViewById(R.id.valve6);
today = (TextView) findViewById(R.id.todaydate);
yesterday = (TextView) findViewById(R.id.yesterdattxt);
stop = (TextView) findViewById(R.id.stop);
stoptxt = (TextView) findViewById(R.id.stoptxt);
idle = (TextView) findViewById(R.id.idle);
idletxt = (TextView) findViewById(R.id.idletxt);
normal = (TextView) findViewById(R.id.normal);
normaltxt = (TextView) findViewById(R.id.normaltxt);
overspeed = (TextView) findViewById(R.id.overspeed);
overspeedtxt = (TextView) findViewById(R.id.overtxt);
ontriptxt = (TextView) findViewById(R.id.ontripstxt);
km_yesterday = (TextView) findViewById(R.id.km_yesterday);
km_travelled_yesterday = (TextView) findViewById(R.id.KmTravelledYesterday);
vehicle_count_yesterday = (TextView) findViewById(R.id.vehicleCountYesterday);
no_of_trips_yesterday = (TextView) findViewById(R.id.NooftripsYesterday);
km_yestxt = (TextView) findViewById(R.id.km_yesterday);
comp_txt = (TextView) findViewById(R.id.comp_txt);
vehcle_txt = (TextView) findViewById(R.id.vehicle_txt);
stop.setTypeface(roboto_regular);
stoptxt.setTypeface(roboto_regular);
idle.setTypeface(roboto_regular);
idletxt.setTypeface(roboto_regular);
normal.setTypeface(roboto_regular);
normaltxt.setTypeface(roboto_regular);
overspeed.setTypeface(roboto_regular);
overspeedtxt.setTypeface(roboto_regular);
no_of_trips = (TextView) findViewById(R.id.NooftripsToday);
today.setTypeface(roboto_regular);
yesterday.setTypeface(roboto_regular);
ontriptxt.setTypeface(roboto_regular);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
dateformat = new SimpleDateFormat("dd/MM/yyyy");
formattedDate = df.format(c.getTime());
todayDate = dateformat.format(c.getTime());
today.setText("Today, " + todayDate);
shPreferences = getSharedPreferences(WebServiceHelper.PREFS_NAME, 0);
shEditor = shPreferences.edit();
connectionDetector = new ConnectionDetecter(getApplicationContext());
isInternetPresent = connectionDetector.isConnectingToInternet();
vdetails = new VehicleDetails();
usernameString = shPreferences.getString("Username", "");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);// get
IMEI_Number = telephonyManager.getDeviceId();
clientCode = shPreferences.getString("ClientCode", "");
secretCode = shPreferences.getString("SecretCode", "");
callAsynchronousTask();
/*GetYesterdaysSummaryTask yTask = new GetYesterdaysSummaryTask();
yTask.execute();*/
adapter = new MyPagerAdapter();
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//
device = vd[position].deviceId;
vehicle = vd[position].vehicleNo;
licNo = vd[position].licenseplateNo;
driverId = vd[position].driver_id;
vehicle = vd[position].vehicleId;
driverName = vd[position].driver;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.d(WebServiceHelper.TAG, "Gesture Detector------------->");
return gestureDetector.onTouchEvent(event);
}
};
animMoveleft = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.moveleft);
animMoveright = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.moveright);
animLeft = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move_left);
animRight = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move_right);
km_travelled_yesterday.setVisibility(View.GONE);
yes_vehicle.setVisibility(View.GONE);
vehcle_txt.setVisibility(View.GONE);
Tclick.startAnimation(animMoveright);
Yclick.startAnimation(animMoveleft);
Ylayout.setOnTouchListener(gestureListener);
Tlayout.setOnTouchListener(gestureListener);
}
/*public void invalidate(){
if(vdetails.outlet_status.contentEquals("1")){
valve6.setImageResource(R.drawable.red_tanker);
}else{
valve6.setImageResource(R.drawable.grenn_tanker);
}
}*/
// get yesterdays summary
public class GetYesterdaysSummaryTask extends
AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
// TODO Auto-generated method stub
if (isInternetPresent) {
try {
vdetails = WebServiceHelper.getYesterdaysSummary(
clientCode, secretCode);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
if (vdetails.status_login.contentEquals("success")) {
km_travelled_yesterday
.setText(vdetails.distance_travelled_yesterday);
km_travelled_yesterday.setTypeface(ostwald_bold);
vehicle_count_yesterday
.setText(vdetails.vehicle_count_yesterday);
vehicle_count_yesterday.setTypeface(roboto_regular);
no_of_trips_yesterday
.setText(vdetails.completed_trips_yesterday);
no_of_trips_yesterday.setTypeface(roboto_regular);
km_yestxt.setTypeface(roboto_regular);
comp_txt.setTypeface(roboto_regular);
vehcle_txt.setTypeface(roboto_regular);
GetAllvehicleSummarytask gTask = new GetAllvehicleSummarytask();
gTask.execute();
} else {
Toast.makeText(context, "failed", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "No internet", Toast.LENGTH_LONG)
.show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
public class GetTodaysSummaryTask extends AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.hide();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
// TODO Auto-generated method stub
if (isInternetPresent) {
try {
vdetails = WebServiceHelper.getTankerSummary(clientCode,
secretCode);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
Log.d(WebServiceHelper.TAG, "On Post Execute------------->");
//callAsynchronousTask();
overspeed.setText(vdetails.overspeed_count);
normal.setText(vdetails.normal_count);
idle.setText(vdetails.idle_count);
stop.setText(vdetails.off_count);
// kmtravelled.setTypeface(roboto_regular);
km_yesterday.setTypeface(roboto_regular);
no_of_trips.setText(vdetails.on_trips_today);
no_of_trips.setTypeface(roboto_regular);
//Tclick.invalidate();
if(vdetails.outlet_status.contentEquals("0")){
Log.d(WebServiceHelper.TAG, "Check Green------------->");
valve6.setImageResource(R.drawable.grenn_tanker);
}else if(vdetails.outlet_status.contentEquals("1")){
Log.d(WebServiceHelper.TAG, "Check Red------------->");
valve6.setImageResource(R.drawable.red_tanker);
callAsynchronousTask();
}
//invalidate();
} else if (result.contentEquals("Failure")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return licenseArray.length;
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.sliding_summary_page, null);
license = (TextView) page.findViewById(R.id.licenseSummary);
license.setTypeface(roboto_regular);
license.setText(licenseArray[position]);
TextView driver = (TextView) page.findViewById(R.id.driverSummary);
ImageView img = (ImageView) page.findViewById(R.id.eng_btn);
driver.setTypeface(roboto_regular);
popup = (ImageView) page.findViewById(R.id.pop_button);
TextView kmtravelledtxt = (TextView) page
.findViewById(R.id.kmtravelledtxt);
kmtravelledtxt.setTypeface(roboto_regular);
driver.setText(driverArray[position]);
TextView km = (TextView) page.findViewById(R.id.kmSummary);
if (KmArray[position].equals("null")) {
km.setText("0");
km.setTypeface(roboto_regular);
} else {
km.setText(KmArray[position]);
km.setTypeface(roboto_regular);
}
TextView loc = (TextView) page.findViewById(R.id.locationSummary);
loc.setText(LocArray[position]);
loc.setTypeface(roboto_regular);
TextView en = (TextView) page.findViewById(R.id.engineSummary);
if (engArray[position].equals("0")) {
img.setImageResource(R.drawable.engine_off);
en.setText("OFF");
en.setTypeface(roboto_regular);
} else {
img.setImageResource(R.drawable.engine_on);
en.setText("ON");
en.setTypeface(roboto_regular);
}
TextView ac = (TextView) page.findViewById(R.id.acSummary);
if (acArray[position].equals("0")) {
ac.setText("OFF");
ac.setTypeface(roboto_regular);
} else {
ac.setText("ON");
ac.setTypeface(roboto_regular);
}
device = vd[0].deviceId;
vehicle = vd[0].vehicleId;
licNo = vd[0].licenseplateNo;
driverId = vd[0].driver_id;
driverName = vd[0].driver;
popup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String[] values = new String[] { "Live Tracking",
"Vehicle Profile", "Driver Profile" };
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.vts_popup);
ListView lv = (ListView) dialog
.findViewById(R.id.list_popupmenu);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
context, android.R.layout.simple_list_item_1,
android.R.id.text1, values) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View view = super.getView(position, convertView,
parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
/* YOUR CHOICE OF COLOR */
textView.setTextColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
return view;
}
};
// Assign adapter to ListView
lv.setAdapter(adapter);
// dialog_dismiss=(ImageView)dialog.findViewById(R.id.dialog_dismiss);
dialog.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
switch (position) {
case 0: {
Intent moreView = new Intent(context,
Tracking.class);
Bundle bundle = new Bundle();
bundle.putString("device", device);
bundle.putString("vehicle", vehicle);
bundle.putString("License No", licNo);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
// finish();
break;
}
case 1: {
Intent moreView = new Intent(context,
Vehicle_Profile.class);
Bundle bundle = new Bundle();
bundle.putString("device", device);
bundle.putString("License No", licNo);
bundle.putString("vehicle", vehicle);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
break;
}
case 2: {
Intent moreView = new Intent(context,
DriverProfile.class);
Bundle bundle = new Bundle();
bundle.putString("driver", driverId);
bundle.putString("DriverName", driverName);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
break;
}
default:
break;
}
}
});
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
// webservice call to get all vehicles
public class GetAllvehicleSummarytask extends
AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
// Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
if (isInternetPresent) {
try {
vd = WebServiceHelper.getAllvehicleSummary(clientCode,
secretCode, usernameString, IMEI_Number,
formattedDate);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
if (VehicleDetails.status_login.equals("success")) {
deviceArray = new String[vd.length];
licenseArray = new String[vd.length];
driverArray = new String[vd.length];
LocArray = new String[vd.length];
KmArray = new String[vd.length];
engArray = new String[vd.length];
acArray = new String[vd.length];
for (int i = 0; i < vd.length; i++) {
licenseArray[i] = vd[i].licenseplateNo;
driverArray[i] = vd[i].driver;
LocArray[i] = vd[i].location_travell;
KmArray[i] = vd[i].km_travelled;
deviceArray[i] = vd[i].deviceId;
engArray[i] = vd[i].en_stat;
acArray[i] = vd[i].ac_stat;
}
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (VehicleDetails.status_login.equals("failed")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
} else if (result.contentEquals("Failure")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
// to get gesture
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
first.setVisibility(View.VISIBLE);
overspeed.setVisibility(View.VISIBLE);
overspeedtxt.setVisibility(View.VISIBLE);
vehcle_txt.setVisibility(View.GONE);
yesarrow.setVisibility(View.VISIBLE);
/*GetTodaysSummaryTask task=new GetTodaysSummaryTask();
task.execute();*/
km_travelled_yesterday.setVisibility(View.GONE);
yes_vehicle.setVisibility(View.GONE);
// vehcle_txt.setVisibility(View.GONE);
Tclick.startAnimation(animMoveright);
Yclick.startAnimation(animMoveleft);
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
first.setVisibility(View.GONE);
overspeed.setVisibility(View.GONE);
overspeedtxt.setVisibility(View.GONE);
vehcle_txt.setVisibility(View.VISIBLE);
yes_vehicle.setVisibility(View.VISIBLE);
km_travelled_yesterday.setVisibility(View.VISIBLE);
yes_vehicle.setVisibility(View.VISIBLE);
// vehcle_txt.setVisibility(View.GONE);
km_travelled_yesterday.setVisibility(View.VISIBLE);
yesarrow.setVisibility(View.GONE);
Tclick.startAnimation(animLeft);
Yclick.startAnimation(animRight);
}
} catch (Exception e) {
// nothing
}
return false;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void callAsynchronousTask() {
//Log.d(WebServiceHelper.TAG, "Call Async Task>>>>>>>>>>.");
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (!isCancelled) {
tTask = new GetTodaysSummaryTask();
tTask.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 5000 ms
// ie in every 5 sec
}
}
Here i used an asynchrous task GetTadaysSummary task to update valve status,trips etc.For automatic updation of values i call the GetTodaysSummaryTask using callasynchronous() method using timer in every 5 seconds.But on live testing the values in the from the GetTodaysSummaryTask is not automatically updated.It only changed when we relaunched the activity.
I dont know what the problem.Please help me.thanks in advance.If anything wrong in my question please forgive me.
Seems like you start your ASyncTask from a non UI Thread(here = TimerTask Runnable). As far as I know ASyncTask is designed to run on UI Thread, only the doInBackground() method runs in a seperate Thread.
Check this question/answer, for further information:
Start AsyncTask in TimerTask
I also noticed
if (VehicleDetails.status_login.equals("success"))
cant find the string "success" is initialized anywhere in your code, only a "Success" with capital S...

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