ImageView not showing captured photo android - android

I am new in android development. I have been trying to access the camera, capture a photo, and then return to my activity and show it on an ImageView.
Here is the code of my activity (very simple, it just do that)
public class Profile extends Activity {
private static final int CAMERA_REQUEST = 1337;
private ImageView imagePhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
imagePhoto = (ImageView) findViewById(R.id.imagePhoto);
ImageView photoButton = (ImageView) this.findViewById(R.id.camera);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( requestCode == CAMERA_REQUEST)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image =(ImageView) findViewById(R.id.imagePhoto);
image.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
What I am doing wrong? I search and try so many codes. When I click in the button, the camera shows up, I take a photo, and then I return to the activity but the thumbnail of the photo is not showing in the ImageView "imagePhoto".
Here is the layout for the imagePhoto:
<ImageView
android:id="#+id/imagePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/welcome"
android:layout_marginRight="50dp"
android:layout_marginTop="82dp"
android:layout_toLeftOf="#+id/camera"
android:src="#drawable/add_photo" /> `/* It has another photo, because I was trying to see if it changes */
And this is in my manifest also:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
I tried so many codes! Thanks in advance. I'm using a Samsung device.

Your Code Looks Fine but i want to share mine as it is working for me
This code will also create a folder in your memory and save the image there
here is the code
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =(ImageView) findViewById(R.id.imagePhoto);
// create external folder
createFolder();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1888 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo );
// to create a random image file name
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
String filePath = "/sdcard/PictureFolder/"+fname;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
photo.compress(CompressFormat.PNG, 100, bos);
try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void createFolder()
{
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "PictureFolder";
File RootFile = new File(RootDir);
RootFile.mkdir();
}
}
and only i add this permission
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Camera is giving very big size image on device

In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}

After taking picture returns to previoius activity android

Here i am trying to launch the camera and take a pic and then set it to a ImageView, but I am being returned to the previous activity after clicking the pic. Here is my code:
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
}
protected void onActivityResult(int reqCode,int resCode,Intent data){
if(reqCode == 1 && resCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
ImageView relativeLayout = (ImageView)findViewById(R.id.imageTaken);
if(photo==null){
relativeLayout.setBackgroundColor(Color.CYAN);
}
else {
relativeLayout.setImageBitmap(photo);
}
}
}
You need declare permission in manifest file.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
Your code looks good, please note that you will get a Thumbnail image.
Please follow the instructions mentioned here, http://developer.android.com/training/camera/photobasics.html . All the best
If you are using fragment it will return to parent Activity.Otherwise below link help you.
http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html
Try this. the difference is the super.onActivityResult(requestCode, resultCode, data); which is necessary when using onActivityResult in fragment
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap1 = null;
if (requestCode == 1) {
bitmap1 = (Bitmap) data.getExtras().get("data");
ImageView relativeLayout = (ImageView)findViewById(R.id.imageTaken);
if(photo==null){
relativeLayout.setBackgroundColor(Color.CYAN);
}
else {
relativeLayout.setImageBitmap(photo);
}
}
Hope it helps.
------------------layout_photoactivity.xml-----------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tv_click_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Select Photo"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
-----------PhotoActivity.class----------
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class PhotoActivity extends Activity {
ImageView imageView1;
TextView tv_click_photo;
public static final String SHAre_PREFERENCES = "Prefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_photoactivity);
imageView1 = (ImageView)findViewById(R.id.imageView1);
tv_click_photo = (TextView)findViewById(R.id.tv_click_photo);
tv_click_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Camera_Activity.class);
startActivityForResult(i, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
System.out.println("result:"+result);
SharedPreferences data_preferences = getSharedPreferences(SHAre_PREFERENCES, MODE_PRIVATE);
String Image_Path= data_preferences.getString("Image_Path", "Notavailble");
String imgstr = data_preferences.getString("data", "Notavailble");
File sel = new File(Image_Path);
String file = sel.getAbsolutePath().substring(sel.getAbsolutePath().lastIndexOf("/")+1);
Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
imageView1.setImageBitmap(bitmap);
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
break;
}
}
}
------------------------------activity_camera.xml----------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<SurfaceView
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="100dip"
android:layout_alignParentBottom="true"
android:gravity="center_vertical"
>
<Button
android:id="#+id/btn_cancel"
android:layout_width="120dp"
android:layout_height="40dp"
android:text="CANCEL"
android:onClick="onCancelClick"
android:textColor="#000000"
android:padding="5dp"
android:layout_marginLeft="10dp"
android:background="#EDEDED"
android:textSize="12dp"
/>
<Button
android:id="#+id/btn_capture"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:text="CAPTURE"
android:onClick="onSnapClick"
android:textColor="#000000"
android:padding="5dp"
android:layout_marginRight="10dp"
android:background="#EDEDED"
android:textSize="12dp"
/>
</RelativeLayout>
</RelativeLayout>
-----------------------Camera_Activity.class----------
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class Camera_Activity extends Activity implements SurfaceHolder.Callback, Camera.ShutterCallback, Camera.PictureCallback{
Camera mCamera;
SurfaceView mPreview;
String path, dirpath;
//static int i = 0;
String Image_Path="",StrBase64="";
Button btn_cancel,btn_capture;
public static final String SHAre_PREFERENCES = "Prefs";
int flag=0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
btn_cancel=(Button)findViewById(R.id.btn_cancel);
btn_capture=(Button)findViewById(R.id.btn_capture);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created,
// Thus finishing this will get us to the last viewed activity
finish();
return;
}
mPreview = (SurfaceView)findViewById(R.id.preview);
mPreview.getHolder().addCallback(this);
mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera = Camera.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mCamera.release();
Log.d("CAMERA", "Destroy");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mCamera.stopPreview();
}
public void onCancelClick(View v)
{
if(flag == 0)
{
finish();
}
else
{
Intent returnIntent = new Intent(Camera_Activity.this,PhotoActivity.class);
if (getParent() == null) {
setResult(Activity.RESULT_OK, returnIntent);
} else {
getParent().setResult(Activity.RESULT_OK, returnIntent);
}
finish();
}
}
public void onSnapClick(View v)
{
if(flag == 0)
{
btn_capture.setClickable(false);
mCamera.takePicture(this, null, null, this);
}
else
{
mCamera.startPreview();
btn_capture.setText("CAPTURE");
btn_cancel.setText("CANCEL");
flag =0;
}
}
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
camera.startPreview();
Random j = new Random();
int ii = j.nextInt(1000);
File sd = Environment.getExternalStorageDirectory();
System.out.println("sd:"+sd);
Image_Path = sd.getAbsolutePath().toString()+"/Pic/pic"+ ii + ".jpg";
System.out.println("Image_Path--------------:"+Image_Path);
path = "pic" + ii + ".jpg";
try {
SharedPreferences data_preferences = getSharedPreferences(SHAre_PREFERENCES, MODE_PRIVATE);
Editor editor = data_preferences.edit();
editor.putString("Image_Path",Image_Path);
String str;
str = new String(data, "UTF-8");
editor.putString("data",str);
editor.commit();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(android.os.Environment.MEDIA_MOUNTED != null)//true if sd card is mounted (xternal)
{
//Here we chose external storage
File dir = new File(sd.getAbsolutePath().toString()+"/Pic");
if(!dir.exists())
{
if (dir.mkdirs()) {
Toast toast = Toast.makeText(this,
"Directory successfully created!",
Toast.LENGTH_SHORT);
toast.show();
}
else
{
Toast toast = Toast.makeText(this,
"Directory creation failed!",
Toast.LENGTH_SHORT);
toast.show();
}
}
File file = new File(dir.getPath().toString(), path);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(Camera_Activity.this, "Image saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
else
{
//Here we chose internal storage
try{
FileOutputStream out = openFileOutput(path, Activity.MODE_PRIVATE);
out.write(data);
out.flush();
out.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
btn_capture.setText("RETAKE");
btn_cancel.setText("USE");
btn_capture.setClickable(true);
mCamera.stopPreview();
flag =1;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
Camera.Size selected = sizes.get(0);
//params.setPreviewSize(selected.width, selected.height);
//mCamera.setParameters(params);
// mCamera.setDisplayOrientation(90);
params.set("orientation", "landscape");
mCamera.setParameters(params);
mCamera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try{
mCamera.setPreviewDisplay(mPreview.getHolder());
}catch(Exception e){
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.i("PREVIEW", "surfaceDestroyed");
}
public void onShutter() {
// TODO Auto-generated method stub
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
}
}
Add permissions in AndroidManifest.xml are
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>

Parse.com & Android: How do I save Images to my parse database so that i can use them as a profile picture

I am new at android as well as parse.com. I need a way in which a user can click a button to take a photo or another button to choose a photo from the gallery. Then store the image in my parse.com database so that I can manipulate it with other events in the system. So far I am able to have the user update his status and save to my parse database but I do not know how to manipulate images and ImageViews. Here is my code so far:
public class UpdateActivity extends Activity {
protected EditText mUpdateStatus;
protected Button mUpdateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//initialization of variables
mUpdateStatus=(EditText)findViewById(R.id.updateStatusUpdate);
mUpdateStatusButton=(Button)findViewById(R.id.updateButtonUpdate);
//code update button click event
mUpdateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get current user
ParseUser currentUser=ParseUser.getCurrentUser();//Identifies current user
String currentUserUsername=currentUser.getUsername();//stores username in variable
//Create new variable to store strings
String newStatus=mUpdateStatus.getText().toString();
//Event for an empty status
if (newStatus.isEmpty())
{AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage("STATUS SHOULD NOT BE EMPTY.");
builder.setTitle("OOPS!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();}
else{
//Save the status in Parse.com
ParseObject statusObject = new ParseObject("Status");//Create a new parse class
statusObject.put("newStatus",newStatus);//Creates a new attribute and adds value from newStatus
statusObject.put("User",currentUserUsername);//Stores username in new parse class
//Save data and initiate callback method
statusObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
{//Event for a Successful storage
Toast.makeText(UpdateActivity.this,getString(R.string.succssfulUpdate),Toast.LENGTH_LONG).show();
//Take user back to profile
Intent main = new Intent(UpdateActivity.this, ProfileActivity.class);
UpdateActivity.this.startActivity(main);
}
else
{//Event for an Unsuccessful storage
AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("SORRY!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
}
});}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.logoutUpdateMenu:
{//logout the user
ParseUser.logOut();
//Take user back to login
Intent intent = new Intent(UpdateActivity.this, LoginActivity.class);
UpdateActivity.this.startActivity(intent);
UpdateActivity.this.finish();
Toast.makeText(getApplicationContext(), getString(R.string.logout_text), Toast.LENGTH_LONG).show();
break;}
}
return super.onOptionsItemSelected(item);
}
}
A complete example image upload for Parse.com with option to take a photo gallery or the camera.
Activity.class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_CAMERA_IMAGE = 2;
private static int RESULT_LOAD_GALLERY_IMAGE = 1;
private String mCurrentPhotoPath;
private ImageView imgPhoto;
private Button btnUploadImage;
private File cameraImageFile;
private TextView mTextView;
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_LOAD_GALLERY_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
} else if (requestCode == RESULT_LOAD_CAMERA_IMAGE) {
mCurrentPhotoPath = cameraImageFile.getAbsolutePath();
}
File image = new File(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
imgPhoto.setImageBitmap(bitmap);
}
}
private File createImageFile () throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File folder = new File(storageDir.getAbsolutePath() + "/PlayIOFolder");
if (!folder.exists()) {
folder.mkdir();
}
cameraImageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
folder /* directory */
);
return cameraImageFile;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
imgPhoto.setOnClickListener(chooseImageListener);
btnUploadImage = (Button)findViewById(R.id.btnUpload);
btnUploadImage.setOnClickListener(uploadListener);
}
View.OnClickListener chooseImageListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogChooseFrom();
}
};
View.OnClickListener uploadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] image = null;
try {
image = readInFile(mCurrentPhotoPath);
}
catch(Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_LONG).show();
}
});
}
};
private void dialogChooseFrom(){
final CharSequence[] items={"From Gallery","From Camera"};
AlertDialog.Builder chooseDialog =new AlertDialog.Builder(this);
chooseDialog.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(items[which].equals("From Gallery")){
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_GALLERY_IMAGE);
} else {
try {
File photoFile = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, RESULT_LOAD_CAMERA_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
chooseDialog.show();
}
private byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#ccc">
<ImageView
android:id="#+id/imgPhoto"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:text="Choose a image"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<Button
android:id="#+id/btnUpload"
android:text="Upload Photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:
public void onClickTakePhoto(View view) {
dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ParseObject statusObject = new ParseObject("Status");
//I think parse has similar support If not this
statusObject.put("profile_photo",imageBitmap);
statusObject.saveInBackground( new Callback(){...});
}
}
You need to convert your Bitmap or any Object into byte[].
And then use following code.
byte[] image= your byte array
final ParseFile files = new ParseFile(image);
files.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException exception) {
if (exception == null) {
ParseUser.getCurrentUser().put("<parse-column-name>", files);
ParseUser.getCurrentUser().saveInBackground();
}
}
});
Hope this helps.
This is how you can upload a file to a Parse server (Back4App):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newProfileImageBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapData = bos.toByteArray();
ParseFile newImageFile = new ParseFile(bitmapData);
currentUser.put("userPicture", newImageFile);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
// Image has been uploaded
} else {
// An error has happened when upoading
}
}
});

Problems when loading cameraimages in imageView

When I take a picture, the picture will saved on the SD.(This works very well)
But the picture won´t shows in the imageView. Do you have any idea?
package de.example.Camera;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Cam extends Activity {
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_cam);
Button button2 = (Button) findViewById(R.id.photo);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start ActivityTwo
/*
* Intent intent = new Intent(getApplicationContext(),
* ActivityTwo.class); intent.putExtra("MyStringValue",
* editText1.getText().toString()); startActivity(intent);
*/
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
}else {
// The picture was returned
Bundle extras = intent.getExtras();
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
private Uri getOutputMediaFile() throws IOException {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DayTwentyNine");
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
if (mediaFile.exists() == false) {
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
}
return Uri.fromFile(mediaFile);
}
}
In the manifest I have are the following:
uses-feature android:name="android.hardware.camera" android:required="false"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here I have this peace of code that works fine the first function open the camera and take the picture and the second one place the image you took into an image view...
public void takePictu(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
photo3 = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo3);
imageView.buildDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo3.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
}

Camera Launching cancelled.Camera app

Hey I am new to android and eclipse environment.I've no idea of Java.I'm trying to create an app to open the camera of an android device.This is how my main activity.java looks like
package com.example.trycamera2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_send);*****
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/xray");
dir.mkdirs();
File file = new File(dir, "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bitmap tempBitmap = (Bitmap) data.getExtras().get("data");
FileOutputStream out;
try {
out = new FileOutputStream(fileUri.getPath());
tempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.v("ManageImage-other", "another phone type");
e.printStackTrace();
}
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
}
There is a red mark under button_send in the star marked line...it shows an alternative action_settings instead of button_send....but when I replace with action_settings and run the launch is cancelled.Failed to install .apk on emulator..any help will be of great use.
Sounds like Android can't find your button in any of the layouts. Double check your layouts to make sure they're there.
If they are, just go to the Project menu at the top, and select Clean. Select your project, then click Okay. It will take moment to clean and build, but that might fix your issue.

Categories

Resources