Crash app For Android kitkat in Camera app in android - android

i Develop custom camera app in android but when i store image in external storage .and android 2.3 to 4.2.0 is complete work but android kitkat version not working .what's problem . my custom camera activity code below.
Please Help me!!
public class CameraActivity extends Activity {
Camera mCamera;
CameraPreview mCameraPreview;
protected static final int MEDIA_TYPE_IMAGE = 0;
static String FilePAth = "";
Button takePicture, btnGlr, btnCancelCamera;
static String base64string = "";
String ImageType;
Boolean isSDPresent;
final int RESULT_LOAD_IMAGE = 1;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
isSDPresent = android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
takePicture = (Button) findViewById(R.id.btnTakePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
Intent intent = getIntent();
if (intent.hasExtra("ImageType")) {
ImageType = getIntent().getStringExtra("ImageType").toString();
Log.v("log", " ImageType in Camera Activity -- > " + ImageType);
}
btnGlr = (Button) findViewById(R.id.btnGallary);
btnGlr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
btnCancelCamera = (Button) findViewById(R.id.btnCancelCamera);
btnCancelCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplication(),
MarketPlaceActivity.class);
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
releaseCamera();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
private Camera getCameraInstance() {
try {
Log.v("log_tag", "camera try:::" + mCamera);
mCamera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
Log.v("log_tag", "camera catch:::" + mCamera);
releaseCamera();
}
return mCamera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
Log.v("log", " FilePAth " + FilePAth);
File mediaFile;
mediaFile = new File(FilePAth);
return mediaFile;
}
/*private String SaveImage_Sta(Bitmap finalBitmap, String name) {
if (isSDPresent) {
Log.i("isSDPresent yes", " path is==> " + isSDPresent);
String root = Environment.getExternalStorageDirectory().toString()
+ "/profile";
File myDir = new File(root);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = name + ".jpg";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.i("isSDPresent no ", " path is==> false ");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
file = new File(directory, "profile.jpg");
if (file.exists())
file.delete();
try {
FileOutputStream fos = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file.toString();
}*/
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
if (ImageType.equals("AddPicture")) {
Intent i = new Intent(getBaseContext(),
MarketPlaceActivity.class);
i.putExtra("data", data);
startActivity(i);
} else {
Intent returnIntent = new Intent();
returnIntent.putExtra("data", data);
setResult(RESULT_OK, returnIntent);
CameraActivity.this.finish();
}
// mCamera.startPreview();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("path", FilePAth);
setResult(RESULT_OK, returnIntent);
finish();
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& 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]);
String picturePath = cursor.getString(columnIndex);
Log.v("log", " picturePath --> selected Gallary Image path --> "
+ picturePath);
cursor.close();
InputStream iStream;
byte[] inputData = null;
try {
iStream = getContentResolver().openInputStream(selectedImage);
inputData = getBytes(iStream);
Log.v("log", " selected Gallary Image ByteArray --> "
+ inputData);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (ImageType.equals("AddPicture")) {
Intent i = new Intent(getBaseContext(),
MarketPlaceActivity.class);
i.putExtra("data", inputData);
i.putExtra("image_from", "Gallary");
startActivity(i);
} else {
Intent returnIntent = new Intent();
returnIntent.putExtra("data", inputData);
returnIntent.putExtra("image_from", "Gallary");
setResult(RESULT_OK, returnIntent);
CameraActivity.this.finish();
}
// ImageView imageView = (ImageView) findViewById(R.id.imgView);
// imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}

As I said in my comment, Android 4.4 (KitKat) has changed how permissions are handled on the SD card. It is now best practice to make your own directory on the SD card to handle all files your app needs to write. Right now you are trying to access the Pictures folder which is not owned or created by your app. Change your getOutputMediaFile() contents to this:
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/MyCameraApp/");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdir();
}
return mediaStorageDir;
}

Related

How to show preview of the image clicked?

using custom camera how can we show the preview of the fullsize image after the image is being clicked from camera clicked and in preview if we can show whether to accept the image or discard the image before saving it to SD card.(Hint: As used in watsapp)
You will get image in byte[], you can convert this byte[] into bitmap and can show it in ImageView
Bitmap bitmap = BitmapFactory.decodeByteArray(yourbytearray, 0, yourbytearray.length);
The complete code according to your requirement is given below. Just follow this.Here uImage is Bitmap and imageView is the imageview where your image will be displayed.
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddownRecipeFromHome.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
uImage = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(uImage);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
uImage.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
uImage = (BitmapFactory.decodeFile(picturePath));
Log.e("path of imag", ""+picturePath);
imageView.setImageBitmap(uImage);
}
else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
imageView.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}

The output of bitmap always show null in android form

I have problem with java class android for upload a file to a remote server.
In the form I select the file on gallery image on smartphone, but the output of bitmap always show null and the form start is blocked.
Log.d("HomeActivity.class", "Output: " + bitmap);
This is beginning to make me believe my structure as a whole is not correct.
What am I missing ?
What's wrong with the code?
I would greatly appreciate any help you can give me in working this problem.
public class HomeActivity extends Activity {
Button btnSend;
Spinner area;
EditText description;
ImageView viewImage;
Button b, upload;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
b = (Button) findViewById(R.id.btnSelectPhoto);
viewImage = (ImageView) findViewById(R.id.viewImage);
upload = (Button) findViewById(R.id.button1);
area = (Spinner) findViewById(R.id.my_spinner_new);
description = (EditText) findViewById(R.id.editText);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (area.getSelectedItem().toString().trim()
.equalsIgnoreCase("Select area")) {
Toast.makeText(HomeActivity.this, "Area.",
Toast.LENGTH_SHORT).show();
} else if (description.getText().toString().length() <= 0) {
description.setError("description");
} else if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"pic", Toast.LENGTH_SHORT)
.show();
Log.d("HomeActivity.class", "Output: " + bitmap);
} else {
ProgressDialog.show(HomeActivity.this,
"Uploading" + bitmap, "Please wait...", true);
}
}
});
new Thread() {
#Override
public void run() {
String path = "http://localhost/list.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u
.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[5120 * 512];
in.read(buffer);
bo.write(buffer);
String s = bo.toString();
final Vector<String> str = new Vector<String>();
String[] line = s.split("\n");
int index = 0;
while (index < line.length) {
str.add(line[index]);
index++;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Spinner spinner = (Spinner) findViewById(R.id.my_spinner_new);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
HomeActivity.this,
android.R.layout.simple_spinner_item, str);
spinner.setAdapter(adapter);
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
Log.d("HomeActivity.class", "Valore restituito: " + bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
edit#1
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (area.getSelectedItem().toString().trim()
.equalsIgnoreCase("Select area")) {
Toast.makeText(HomeActivity.this, "Area.",
Toast.LENGTH_SHORT).show();
} else if (description.getText().toString().length() <= 0) {
description.setError("description");
} else if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"pic", Toast.LENGTH_SHORT)
.show();
Log.d("HomeActivity.class", "Output: " + bitmap);
} else {
ProgressDialog.show(HomeActivity.this,
"Uploading" + bitmap, "Please wait...", true);
}
}
});
You are starting your upload thread in onCreate. And so bitmap is null. Better start your thread in an onClick handler.
By the way: Log.d("HomeActivity.class", "Output: " + bitmap);. That is awfull trying to print a bitmap. If you want to check if the bitmap is null the do so:
if ( bitmap==null )
Log.d(TAG, "bitmap==null");
else
Log.d(TAG, "we have a nice bitmap");

How do I get the image that I took and submit it to my server

Currently I am able to upload an existed image in the sdcard to my server. I'm a total newbie in Android programming world and I was wondering how do I dynamically grab the newly taken image and submit it to the server?
This is what I have so far for my onClick event
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
new Thread(new Runnable() {
public void run() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
//hard code
String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";
int response= uploadFile(path);
System.out.println("RES : " + response);
}
}).start();
}});
This is the codes for my camera functions
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
outStream.write(arg0);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
//VuzixCamera.super.onBackPressed();
}
camera.startPreview();
}};
Hope this answer will help you.
Take A new Picture Code:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class CameraUtil extends Activity {
private final static int REQUEST_TAKE_PHOTO=200;
private final String TAG = "Camera";
String mCurrentPhotoPath;
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(! isDeviceSupportCamera()){
Log.e(TAG,"Camera Not Supported");
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
}
else{
dispatchTakePictureIntent();
}
}
private void dispatchTakePictureIntent() {
Log.i(TAG,"Dispatch Take Picture Intent");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(TAG,"Error occurred while creating the File");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
File file= new File(path);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && path!=null && file.length()>0) {
Intent returnFromCameraIntent = new Intent();
returnFromCameraIntent.putExtra("picturePath",path);
setResult(RESULT_OK,returnFromCameraIntent);
finish();
Log.i(TAG,"Camera Closed");
}else{
Log.i(TAG,"On Result CANCEL");
// cancelled Image capture
try{
/*delete Temperory created file*/
file.delete();
}catch(Exception e){
e.printStackTrace();
}
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
Log.i(TAG,"Image Capture Cancelled");
}
galleryAddPic();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
String imageFileName = "CAMERA_" + timeStamp + "_WA0001";
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyApp"+ File.separator);
if(!root.exists()){
root.mkdirs();
}
// File storageDir = Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
root /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
path=""+image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
}
Choose Existing Picture Code:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_LOAD_GALLERY=100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "Gallery_Image";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_GALLERY);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && 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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}else{
Log.i(TAG,"Image Capture Cancelled");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED,returnFromGalleryIntent);
finish();
}
}
}
Convert Image to Base64 String:
public class Base64Utils {
private static final String TAG = "Base64Utils";
private String picturePath;
private String base64;
public Base64Utils(String picturePath) {
this.picturePath = picturePath;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public String getBase64() {
FileInputStream fis11=null;
try {
fis11 = new FileInputStream(picturePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
byte[] buf = new byte[8096];
try {
for (int readNum; (readNum = fis11.read(buf)) != -1;) {
bos11.write(buf, 0, readNum);
}
} catch (IOException ex) {
ex.printStackTrace();
}
bytes = bos11.toByteArray();
base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
public void setBase64(String base64) {
this.base64 = base64;
}
}
Main Activity Code: Choose or Take Picture, convert it to base64 string and Send Base64 String to Server.
public class CapatureImage extends Activity implements View.OnClickListener {
private final String TAG = "CapatureImage";
String picturePath;
String base64 = null,
private ImageButton image;
// for popup
private PopupWindow pop;
private final int GALLERY_ACTIVITY_CODE = 200;
private final int CAMERA_ACTIVITY_CODE = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CapatureImage);
configureComponent();
}
private void configureComponent() {
image = (ImageButton) findViewById(R.id.image);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.image:
initiatePopupWindow();
break;
case R.id.button_camera_dialog:
Intent camera_Intent = new Intent(this.getApplicationContext(),
CameraUtil.class);
pop.dismiss();
this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
break;
case R.id.button_gallery_dialog:
Intent gallery_Intent = new Intent(this.getApplicationContext(),
GalleryUtil.class);
pop.dismiss();
this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
break;
case R.id.button_cancel_dialog:
pop.dismiss();
break;
case R.id.button_remove_dialog:
Log.i(TAG, "Remove Picture");
image.setImageResource(R.drawable.icon_781q);
picturePath=null;
pop.dismiss();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64();
//send this base64 string to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
if (requestCode == CAMERA_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
// Log.i("Camera_Activity", data.toString());
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}// onActivityResult
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialoge_choosephoto,
(ViewGroup) findViewById(R.id.photo_popup));
if (picturePath != null && !picturePath.isEmpty()) {
Log.i(TAG, "Image Exist..Add Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.VISIBLE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
} else {
Log.i(TAG, "No Image..remove Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.GONE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
}
// component for popup
gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
gallery.setOnClickListener(this);
camera = (Button) layout.findViewById(R.id.button_camera_dialog);
camera.setOnClickListener(this);
cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
cancel.setOnClickListener(this);
pop.showAtLocation(layout, Gravity.CENTER, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
void displayImage(String path) {
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
image.setScaleType(ScaleType.CENTER_CROP);
}
}
}
there is two classes upload and main_activity.And i here put it's xml file
public class MainActivity extends Activity {
final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final String TAG = "CaptureImage.java";
public static ImageView showImg = null;
static String uploadFilePath = " ";
static String Path;
static int delete_image_id = 0;
static TextView imageDetails = null;
// FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
static Cursor cursor = null;
public ProgressDialog dialog_upload = null;
public String s_name;
public String s_Adress;
int serverResponseCode = 0;
TextView shift_display;
Uri imageUri = null;
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("VALUES", "It is Working");
String fileName = "Camera_Example.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
};
MainActivity CameraActivity = null;
Upload upload;
Button outlet_names_show;
double latitude;
double longitude;
OnClickListener oclBtnOk3 = new OnClickListener() {
#Override
public void onClick(View v) {
if (showImg.getDrawable() == null) {
Toast.makeText(MainActivity.this, " Picture was not captured ",
Toast.LENGTH_SHORT).show();
} else {
upload_prescription();
// CallSummery.flag_bt_merchan=true;
}
}
};
private Button buttonback;
/**
* ********* Convert Image Uri path to physical path *************
*/
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String[] proj = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.getContentResolver().query(imageUri, proj, null,
null, null);
// Get Query Data
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int file_ColumnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// int orientation_ColumnIndex = cursor.
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
// imageDetails.setText("No Image");
} else {
if (cursor.moveToFirst()) {
imageID = cursor.getInt(columnIndex);
delete_image_id = imageID;
Path = cursor.getString(file_ColumnIndex);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Return Captured Image ImageID ( By this ImageID Image will load from
// sdcard )
return "" + imageID;
}
protected void onCreate(Bundle savedInstanceState) {
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraActivity = this;
showImg = (ImageView) findViewById(R.id.showImg);
upload = new Upload(MainActivity.this);
final Button photo = (Button) findViewById(R.id.photo);
final Button upload = (Button) findViewById(R.id.upload);
photo.setOnClickListener(oclBtnOk);
upload.setOnClickListener(oclBtnOk3);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageUri != null) {
outState.putString("cameraImageUri", imageUri.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
imageUri = Uri
.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void upload_prescription() {
dialog_upload = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
createDirectoryIfNeeded();
upload.uploadFile(uploadFilePath);
}
}).start();
}
private void createDirectoryIfNeeded() {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Capturetemp");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
}
public void copy(String lo, String lan) throws JSONException {
String sdCard = Environment.getExternalStorageDirectory().toString();
Random ran = new Random();
uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";
File sourceLocation = new File(Path);
File targetLocation = new File(uploadFilePath);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if (actionChoice == 1) {
if (sourceLocation.renameTo(targetLocation)) {
Log.v(TAG, "Move file successful.");
} else {
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else {
// make sure the target file exists
if (sourceLocation.exists()) {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
} else {
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ***************/
String imageId = convertImageUriToFile(imageUri, CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard(MainActivity.this).execute(""
+ imageId);
/*********** Load Captured Image And Data End ****************/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBackPressed() {
}
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
Context context;
Bitmap mBitmap;
private ProgressDialog loadingdailog;
public LoadImagesFromSDCard(MainActivity context) {
this.context = context;
}
#Override
protected void onPreExecute() {
loadingdailog = new ProgressDialog(context);
loadingdailog.setMessage("Loading Image.....");
loadingdailog.show();
}
// Call after onPreExecute method
#Override
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
uri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
+ urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
true);
// SaveIamge(newBitmap);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
// Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (loadingdailog.isShowing() && loadingdailog != null) {
loadingdailog.dismiss();
loadingdailog = null;
}
if (mBitmap != null) {
showImg.setImageBitmap(mBitmap);
}
}
}
}
upload class
public class Upload {
protected MainActivity context;
ProgressDialog dialog = null;
int serverResponseCode = 0;
String uploadFilePath = null;
String uploadFileName = null;
String msg = null;
String upLoadServerUri = "http://fileuploadpath";
public Upload(MainActivity context) {
this.context = context;
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("photo", fileName);
// conn.setRequestProperty("session_id","13");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
try {
readStream(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
context.runOnUiThread(new Runnable() {
public void run() {
context.dialog_upload.dismiss();
Toast.makeText(context, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
fileInputStream.close();
} catch (MalformedURLException ex) {
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// context.dialog.dismiss();
e.printStackTrace();
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
// context.dialog.dismiss();
return serverResponseCode;
}
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.e("tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
xml file
<LinearLayout 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:background="#FFFFFF"
android:orientation="vertical"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/showImg"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="bla bla" />
<Button
android:id="#+id/photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Capture Image"
android:textSize="26sp" />
<Button
android:id="#+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Upload Photo"
android:textSize="26sp" />
</LinearLayout>
for image uri you should paste your file upload path

How to send multiple images to another activity in android?

In my application i have created a custom camera where it captures images and save it in sd card. And also can view it in second activity. But it just replaces the previous images which i dont want. How to send multiple images to second activity?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceview);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
click = (Button) findViewById(R.id.button_capture);
click.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
filepath = Environment.getExternalStorageDirectory()+"/testing/"+"test.3gp";
System.out.println("thumbnail path~~~~~~"+filepath);
File file = new File(filepath);
Uri uriTarget = Uri.fromFile(file);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CustomCameraActivity.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",filepath.toString());
setResult(1,returnIntent);
finish();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Just Convert your image into bitmap and pass that Bitmap in another activity by yourIntent.putExra("key",bitmap);
Or Use this:
private File imageFile;
private Uri imageUri;
private static final int CAMERA_REQUEST_CODE = 100;
private String imagePath
private Uri getTempUri() {
// Create an image file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dt = sdf.format(new Date());
imageFile = null;
imageFile = new File(Environment.getExternalStorageDirectory()
+ "/foldername/", "Camera_" + dt + ".jpg");
Applog.Log(
TAG,
"New Camera Image Path:- "
+ Environment.getExternalStorageDirectory()
+ "/foldername/" + "Camera_" + dt + ".jpg");
File file = new File(Environment.getExternalStorageDirectory()
+ "/foldername");
if (!file.exists()) {
file.mkdir();
}
if (!imageFile.exists()) {
try {
imageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath = Environment.getExternalStorageDirectory() + "/foldername/"
+ "Camera_" + dt + ".jpg";
imageUri = Uri.fromFile(imageFile);
return imageUri;
}
Now When you start activty for camera.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
getTempUri());
startActivityForResult(cameraIntent,
CAMERA_REQUEST_CODE);
Now In ActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (CAMERA_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
String yourUri=ImagePath;
//now store this Uri it will contain capture image url.
}
}

how to capture picture portrait mode set portrait mode?

i have camera activity. and i capture picture but in camera preview not show picture portrait mode . how to possible in android . my code below .
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
protected static final int MEDIA_TYPE_IMAGE = 0;
static String FilePAth = "";
Button takePicture;
static String base64string="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
takePicture = (Button) findViewById(R.id.btnTakePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
Log.v("log", " FilePAth " + FilePAth);
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("data", data);
setResult(RESULT_OK, returnIntent);
finish();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("path", FilePAth);
setResult(RESULT_OK, returnIntent);
finish();
};
}
and get data :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("log", " data --> " + data.getByteArrayExtra("data"));
if (requestCode == 1) {
if (data.hasExtra("data")) {
Log.v("log", " request if ");
Bitmap b = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("data"), 0,
data.getByteArrayExtra("data").length);
imgStorePicture.setImageBitmap(b);
/*imgStorePicture.setScaleType(ScaleType.FIT_XY);*/
base64string = Base64.encodeBytes(data
.getByteArrayExtra("data"));
Log.v("log", "base64string " + base64string);
}
}
}
The short answer is, you cannot. The picture is always returned the way it is. You can change preview orientation, but not the orientation of the JPEG image returned to your onPictureTaken).
But you can set JPEG rotation via Exif header without decoding it. This is the most efficient method, but some viewers may still show a rotated image.
Alternatively, you can use JPEG lossless rotation. The Android port is on GitHub.

Categories

Resources