I have an onClick method of a checkbox in a class that extends baseAdapter here:
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = mContext.getApplicationContext().openFileOutput("BitmapImage", Context.MODE_PRIVATE);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "the icon(s) have been saved");
out.close();
// Load back the image file to confirm it works
// Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
// ImageView imageV = (ImageView)findViewById(R.id.);
// imageV.setImageBitmap(bitmap);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
// Intent intent = new Intent (v.getContext(), Drag_and_Drop_App.class);
// v.getContext().startActivity(intent);
// Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
} else {
System.out.println("Un-Checked");
}
}
From what I've seen, I would need an intent from this activity to my other class where I get the created bitmap made in the onClick method above. The issue is that my other class also extends baseadapter so I can't use startActivity().
Here is where I get the bitmap from storage (in other class):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
try {
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = Context.openFileInput("BitmapImage");
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// getThumbnail();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
How can I make it so that I can send intent to my other class so I can get the bitmap?
ADDED:
Does this work the same way? (Please check my coding)
Intent intent = new Intent (v.getContext(), GVABackup.class);
v.getContext().startActivity(intent);
Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
for one class and then
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
Intent intent = new Intent (view.getContext(), GVABackup.class);
view.getContext().startActivity(intent);
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
in my adapter with the GVABackup class like this:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GVABackup extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ImageView view = (ImageView)findViewById(R.id.layout1);
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = null;
try {
in = openFileInput("BitmapImage");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
I don't fully understand what you are asking but would the LocalBroadcastmanager do what you need?
http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
Related
How to handle full-sized photo using MediaStore.EXTRA_OUTPUT? First, I need to put the picture AS FULL-SIZED NOT THUMBNAIL on a layout and put text below it like this:
The idea I am using is that I am using layout.getDrawingCache to make it as bitmap.
Below is my camera button:
private void SelectImage(){
final CharSequence[] items={"Camera", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PickupDrop.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!= null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (Exception e) {
e.printStackTrace();
}
if(imageFile!= null){
imageUri =FileProvider.getUriForFile(context, "com.example.android.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent,REQUEST_CAMERA);
}
}
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
The getImageFile() method:
private File getImageFile(){
String imageName = "test";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
currentImagePath = imageFile.getAbsolutePath();
return imageFile;
}
As you can see above, I am using EXTRA_OUTPUT with fileprovider to get FULL-SIZED bitmap.
Below is my manifests, provider.
Manifest:
<application ...
<provider
android:authorities="com.example.android.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"/>
</provider>
file_path.xml:
<?xml version="1.0" encoding="utf-8"?>
<external-path
name="my images"
path="Android/data/com.example.luckypasabayapp/files/Pictures"/>
My onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
populateScreenshot(bitmap);
}
}
}
Now here is where my problem occurs when I try to save the relative layout screenshot to my storage:
public void populateScreenshot(Bitmap bitmapFromPhone){
LayoutInflater inflater = LayoutInflater.from(PickupDrop.this);
View v = inflater.inflate(R.layout.information_dialog, null);
ImageView imageView_profilePic = v.findViewById(R.id.imageview_image);
TextView txt_item_data = v.findViewById(R.id.txt_item_data);
Button btn_cancel = v.findViewById(R.id.btn_cancel);
Button btn_download = v.findViewById(R.id.btn_download);
screenShot = v.findViewById(R.id.screenShot);
screenShot.setDrawingCacheEnabled(true);
screenShot.buildDrawingCache();
final AlertDialog alertDialog = new AlertDialog.Builder(PickupDrop.this)
.setView(v)
.create();
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Prevent dialog close on back press button
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
//alertDialog.setCanceledOnTouchOutside(false);
//SETTING THE IMAGEVIEW OF LAYOUT TAKEN FROM CAMERA
imageView_profilePic.setImageBitmap(bitmapFromPhone);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//GETTING THE RELATIVELAYOUT AS BITMAP
Bitmap bitmap = screenShot.getDrawingCache();
File filePath = Environment.getExternalStorageDirectory();
File dir = new File(filePath.getAbsolutePath()+"/qrcode/");
dir.mkdirs();
File file = new File(dir, "str_specialNumber" + ".png");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//HERE IS WHERE THE ERROR OCCURS, IT SAYS BITMAP IS NULL!!!
bitmap.setHasAlpha(true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,outputStream);
Toast.makeText(PickupDrop.this,"SCREENSHOT Downloaded",Toast.LENGTH_LONG).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//notify gallery for a new picture
galleryAddPic(filePath.getAbsolutePath()+"/qrcode/"+"str_specialNumber"+".png");
}
});
alertDialog.show();
}
Here in bitmap.setHasAlpha(true); it says bitmap is null from screenshot.getDrawingCache I don't understand why.
How do I handle the EXTRA_OUTPUT properly to be able to do whatever I want with the bitmap?
You can give this answer a try :)
If you want to take the screenshot of any view or your RelativeLayout you can create this method takeScreenShot() : it will return a Bitmap
in #Param or parameter in this method, you can pass RelativeLayout
public static Bitmap takeScreenShot(#NonNull View view) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
view.buildDrawingCache();
if (view.getDrawingCache() == null) return null;
Bitmap snapshot;
try {
snapshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
} catch (Exception e) {
snapshot = null;
}
return snapshot;
}
tell me if this helps you :)
I am creating a soundboard app. The app will feature different "pages" (fragments) that the user can switch between. Each fragment has a number of ImageButtons that, when clicked on, will play a sound.
I put the following code first inside of the MainActivity inside the OnCreate method. After that failed I realized that I'd probably have to put that code inside of each fragment inside the fragment's OnCreateView method.
After doing so I come up for an error for the "findViewById" method. I corrected this by using the "getView()" method directly before the "findViewById" method.
Now I have an error on the "final MediaPlayer player = new MediaPlayer();". The error says that this is an unreachable statement.
I have no idea how to fix this... what can I do to correct this error?
FragmentPage1.java
public static class FragmentPage1 extends Fragment {
int selectedSoundId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page1, container, false);
return rootView;
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
final int[] buttonIds = { R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9 };
final int[] soundIds = { R.raw.num_21, R.raw.whats_9_plus_10, R.raw.a_potato_flew_around_my_room, R.raw.a_week_ago, R.raw.aint_nobody_got_time_for_dat, R.raw.awww, R.raw.baby_lip, R.raw.backflip, R.raw.baliegdeh };
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
break;
}
}
}
};
for (int i = 0; i < buttonIds.length; i++) {
ImageButton soundButton = (ImageButton) getView().findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The statement is unreachable because you unconditionally return before it can be reached. The fix is simple: move return rootView to the end of the method and instead of getView() use rootView.
I'm using the universal image loader for my app. I want to save the current image displayed by the ViewPager to the SD-Card however the code I have below is saving the wrong image to the SD-Card. It saves the images at random only. I need to way of knowing how to retrieve the current bitmap of the image and saving it. I don't know any other alternatives of getting the bitmap of the current image and saving it to the SD-Card. The way I'm getting the bitmap currently is through "Bitmap bitmap = loadedImage". Your help would be greatly appreciated. Cheeers.
public class ImagePagerFragment extends BaseFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_pager, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new ImageAdapter());
pager.setCurrentItem(getArguments().getInt(Constants.Extra.IMAGE_POSITION, 0));
return rootView;
}
private class ImageAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
final christ.triumphant.TouchImageView imageView = (christ.triumphant.TouchImageView) imageLayout.findViewById(R.id.imagei);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {
..
#Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
isave = (Button) getView().findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap bitmap = loadedImage;
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
File f = new File(folder, String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Image Successfully Saved", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File ff = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(ff);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
else
{
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ishare = (Button) getView().findViewById(R.id.share);
ishare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap icon = loadedImage;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Toast.makeText(getActivity(), "Image Successfully Shared", Toast.LENGTH_LONG).show();
}
});
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
... ... ... }
I'm quit scared with this application. I'm developing an application that changes the contact photo with from image-view. It doesn't generate any error but does not even change contact image. I have a doubt, if it's the OnActivityResult() method. Please correct me on that. Here is the code of OnActivityResult() method.
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case IMAGE_PICK:
this.imageFromGallery(resultCode, data);
break;
case IMAGE_CAPTURE:
this.imageFromCamera(resultCode, data);
break;
case PICK_PHOTO:
if(resultCode == RESULT_OK){
// Getting the uri of the picked photo
Uri updateImageView = data.getData();
InputStream imageStream = null;
try {
// Getting InputStream of the selected image
imageStream = getContentResolver().openInputStream(updateImageView);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Creating bitmap of the selected image from its inputstream
image = BitmapFactory.decodeStream(imageStream);
// Getting reference to ImageView
// ImageButton ibPhoto = (ImageButton) findViewById(R.id.photo);
// Setting Bitmap to ImageButton
photo.setImageBitmap(image);
}
break;
default:
break;
}
}
}
also here is my onClick() code.
save.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int position=getIntent().getExtras().getInt("bmp");
int po=ops.size();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(image!=null)
{ // If an image is selected successfully
image.compress(Bitmap.CompressFormat.PNG , 100, stream);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG , 75, stream);
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, position) // here position is _ID where I'm inserting image
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO,stream.toByteArray())
.build());
try {
stream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.d("Image Null", "True");
}
try{
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY,ops);
Toast.makeText(getBaseContext(), "Contact Image change successfully", Toast.LENGTH_SHORT).show();
}
catch (RemoteException e) {
e.printStackTrace();
}catch (OperationApplicationException e) {
e.printStackTrace();
}
} });
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);
}
}