I ran into an issue with something that I am probably just overlooking.
I want to take a picture from the surface preview of the camera, and save it to the sd_card. This works ALMOST perfect. I assigned it a file name, but it does not use the filename.
This is what I have been trying to do :
Button imagecapture = (Button) findViewById(R.id.imagecapture);
imagecapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String filename = null;
ImageCaptureCallback iccb = null;
try {
filename = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(Media.TITLE, filename);
values.put(Media.DESCRIPTION, "Image capture by camera");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
iccb = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
} catch (Exception ex) {
ex.printStackTrace();
Log.e(getClass().getSimpleName(), ex.getMessage(), ex);
}
camera.takePicture(mShutterCallback, mPictureCallbackRaw, iccb);
com.froogloid.android.gspot.Park.imageFileName = filename;
}
});
It won't use the filename (i.e. time/date stamp I ask it to.)
This was resolved by implementing PictureCallback via a ImageCaptureCallback class, and Overriding the onPictureTaken where the file was being written via a file output stream. All you had to do was change the fileoutput stream to the filename you want.
it doesn't save image? in my app this code saves image, maybe you use variable "filaname" to get image from sdcard? to use image from sdcard is better to save in variable, for examople, "fileUri" value of uri.toString, end get from sdcard file with uri Uri.parse(fileUri)..
Hope this helps / Probably not the best way to go about it, but it worked.
Here you go:
This is the camera capture image callback.
public class ImageCaptureCallback implements PictureCallback {
private OutputStream filoutputStream;
public ImageCaptureCallback(OutputStream filoutputStream) {
this.filoutputStream = filoutputStream;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Log.v(getClass().getSimpleName(), "onPictureTaken=" + data + " length = " + data.length);
FileOutputStream buf = new FileOutputStream("/sdcard/dcim/Camera/" + CameraActivity.filename + ".jpg");
buf.write(data);
buf.flush();
buf.close();
// filoutputStream.write(data);
filoutputStream.flush();
filoutputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Related
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
// Log.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
// Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
// Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
I have used above code to save generated QR in Gallery. and it is working too.
But it is saving in Internal Storage/package_name/Files/mtImage.jpg.
I have to go to file manager in order to view it. I want to view it directly in Gallery and I don't have any SD card.
Please help me with this.
Below code helps to save bitmap image to gallery
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
Hi I am trying to make the images captured from my app inaccessible to the user. First I tried to save these images to internal storage which didnt work. Then I tried to hide them using "." infront of the folder name.I am not sure what the correct way to do this is. I also tried creating a file called .nomedia to bypass media scanner. I am very confused about the proper way to do this. Here's my code:
public String getImageUri(Context inContext, Bitmap inImage) {
/* *//* ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, ".title", null);
return Uri.parse(path);*//*
*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.myFolder");
file.mkdirs();
File mFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.nomedia");
mFile.mkdirs();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
uri = MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
If I use file.mkdirs() I get filenotfoundexception. If i remove that line I get no errors but my uri is empty.
Does the above function return the file path as well? I need the file path and the uri later on. Any help is appreciated.
I guess you don't have to add another extension or something else just save them in external cache dir of your app and gallery app won't able to read your private directory until unless you notify about them.
so store your camera images here and no gallery app can detect it.
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
sample code
public static File createPictureFile(Context context) throws IOException {
Locale locale = Locale.getDefault();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", locale).format(new Date());
String fileName = "JPEG_" + timeStamp + "_";
// Store in normal camera directory
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(fileName, ".jpg", storageDir);
}
Save your image to internal storage instead. Other applications like MediaScanner or Gallery do not have permission to read from your own application memory. Sample code:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Save the image with different extension.
For example: .jpg can be saved as .ttj.
Try this code. Set where you want to save the photo. Once you receive response on onActivityResult(), in the desired URI, you will get the photo.
public void captureImageFromCamera() {
fileUri = FileUtils.getInstance().getOutputMediaFile(null);
if(fileUri == null){
Utilities.displayToastMessage(ApplicationNekt.getContext(),
context.getString(R.string.unable_to_access_image));
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Following function will give you desired path. Change it based on your project need.
public Uri getOutputMediaFile(String imageNameWithExtension) {
if (imageNameWithExtension == null)
imageNameWithExtension = "image_" + System.currentTimeMillis() + ".jpg";
String extPicDir = getExtDirPicturesPath();
if (!Utilities.isNullOrEmpty(extPicDir)) {
File mediaFile = new File(extPicDir, imageNameWithExtension);
return Uri.fromFile(mediaFile);
} else {
Log.d("tag", "getOutputMediaFile." +
"Empty external path received.");
return null;
}
}
public String getExtDirPicturesPath() {
File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file != null)
return file.getPath();
else
Log.d("", "getExtDirPicturesPath failed. Storage state: "
+ Environment.getExternalStorageState());
return null;
}
To get the resultant photo.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case TAKE_PICTURE:
//fileuri variable has the path to your image.
break;
}
I have a application that takes photo shots as well as displays a imageview like a frame. What I want to do is to merge the imageview with the data in the PictureCallback, I have read multiple tutorials but I find them difficult. Is it possible to merge and save the image in the code below? Some sample will be helpful!
private Camera.PictureCallback mPicJpgListener = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
if (data == null) {
return;
}
String saveDir = Environment.getExternalStorageDirectory().getPath() + "/test";
// retrieve the folder
File file = new File(saveDir);
// creating a folder
if (!file.exists()) {
if (!file.mkdir()) {
Log.e("Debug", "Make Dir Error");
}
}
// saving the Path
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String imgPath = saveDir + "/" + sf.format(cal.getTime()) + ".jpg";
// ファイル保存
FileOutputStream fos;
try {
fos = new FileOutputStream(imgPath, true);
//I want to merge the ImageView
fos.write(data); //writing the data
fos.close();
registAndroidDB(imgPath);
} catch (Exception e) {
Log.e("Debug", e.getMessage());
}
fos = null;
mCam.startPreview();
mIsTake = false;
}
};
I'm trying to retrieve an image that I (think) I have saved using a surfaceview in a fragment (nightmare) in Android. Here I try to save an image and list all the images in the directory. I've not absolutely no clue where the directory is (storate/emulated/0 etc). I can never find the images anywhere except listing them like this. Which suggests to me that they probably exist?
jpegCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Create an image file name
File image = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
try {
image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
String filename = "";
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName "+i+" :" + file[i].getName());
filename = file[i].getName();
}
Bitmap myBitmap = BitmapFactory.decodeFile(file[0].getAbsolutePath()+"/"+filename);
ImageView taken_pic = (ImageView) view.findViewById(R.id.taken_pic);
taken_pic.setImageBitmap(myBitmap);
}
};
This just gets me a list of image names and an 'SkImageDecoder::Factory returned null' message. I may have made things worse with the filename string, but even hardcoding in one of the files in the list that is echoed out I get the same results. Should the images exist based on the results of this code? How can I actually get the images again as bitmaps? Is there a better way to do this. I've tried every example I can find and read every topic.
This is my now working example of a button that will work with a surfaceview which is displaying the camera to correctly save an image (currently to downloads folder), retrieve it and output it to an imageview (currently "taken_pic").
Not sure exactly where I was going wrong. I think just in several small places. A big issue is the difficulty in debugging this. My phone is not rooted so I think my options with Android Studios Device Monitor were limited. Often you won't see images that have been saved when browsing via a PC explorer. Remove the USB, restart the phone and the files should appear where they should be.
I hope this may be of help to someone.
camera_picture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
private void captureImage() {
cam.takePicture(shutterCallback, rawCallback, jpegCallback);
}
rawCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Log", "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
shutterCallback = new Camera.ShutterCallback() {
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
File fileb = new File(android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "imagename2.jpg");
outStream = new FileOutputStream(fileb);
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d("Log", "onPictureTaken - jpeg");
String photoPath = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/imagename.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
ImageView taken_pic = (ImageView) view.findViewById(R.id.taken_pic);
taken_pic.setImageBitmap(bitmap);
}
is it possible to launch unity from an android activity passing an image and then using that image as a sprite? e.g using something like:
Intent i = new Intent(this, UnityActivity.class);
i.putExtra(imageFile);
startActivity(i);
And if this is possible how do you handle the received image in unity?
Thanks
I solved my own problem by saving the image to a specific location in the android activity:
private static boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/gameFiles/myImages/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + "/" + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
And then I used this image to create a sprite in unity by referencing the location I had saved the file in the android activity:
IEnumerator Start()
{
string path = "file:///mnt//sdcard//gameFiles//myImages//img.png";
WWW www = new WWW(path);
yield return www;
SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
Sprite sprite = new Sprite();
sprite = Sprite.Create(www.texture, new Rect(-0.7f, -0.7f, 330, 440), new Vector2(0.5f, 0.5f), 150.0f);
renderer.sprite = sprite;
Time.timeScale = 0;
}