Im trying to capture image and then for good practice I put bitmap file in the the FileOutputStream how can I recover the bitmap using the filename.
Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == REQUEST_CODE_CAMERA && data != null){
fragment = null;
Bitmap bmp = (Bitmap) data.getExtras().get("data");
String filename = "bitmap.png";
try {
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
stream.close();
bmp.recycle();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left,R.anim.fade_out,R.anim.fade_in,R.anim.slide_out_right);
fragment =FragmentCropper.newInstance(filename);
fragmentTransaction.add(R.id.fragmentContainer,fragment,Constant.BackStackTag.CROP_TAG);
fragmentTransaction.addToBackStack(Constant.BackStackTag.CROP_TAG);
fragmentTransaction.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the Fragment
How to recover the Bitmap using the filename
try {
//FileInputStream stream = getActivity().openFileInput(filename);
//mBitmap = BitmapFactory.decodeStream(stream);
//stream.close();
String path = "path/"+filename;
mBitmap = BitmapUtils.decodeSampledBitmapFromFile(path,500,500);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (mBitmap.isRecycled())
mBitmap.recycle();
mBitmap=null;
}
String path = "path/"+filename;
Change to
String path = getFilesDir().getAbsolutePath() + "/" + filename;
Related
I opened the music player to select an audio file using this code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
}
});
I called the uploadAudioToParse method inside OnActivityResult()
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
File abc=new File(uri.toString());
ParseObject ob=new ParseObject("songs");
uploadAudioToParse(abc,ob,"song");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
And this is my uploadAudioToParse method.
private ParseObject uploadAudioToParse(File audioFile, ParseObject po, String columnName){
if(audioFile != null){
Log.d("EB", "audioFile is not NULL: " + audioFile.toString());
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(audioFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int read;
byte[] buff = new byte[1024];
try {
assert in != null;
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] audioBytes = out.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile(audioFile.getName() , audioBytes);
po.put(columnName, file);
// Upload the file into Parse Cloud
file.saveInBackground();
po.saveInBackground();
}
return po;
}
is the file conversion method correct?
I'm having a problem writing and reading files.
Here goes the code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch(requestCode) {
case INTENT_COUNTRY:
if (data.getExtras().containsKey("country")) {
final String c = data.getStringExtra("country");
Log.d("Profile", "Country: " + c);
txtCountry.setText(c);
}
break;
case PICKER_CAMERA:
Log.d("Profile", "PICKER_CAMERA");
Bitmap bitmapCamera = (Bitmap) data.getExtras().get("data");
Bitmap thumbnailCamera = ThumbnailUtils.extractThumbnail(bitmapCamera, 320, 320);
ByteArrayOutputStream streamCamera = new ByteArrayOutputStream();
thumbnailCamera.compress(Bitmap.CompressFormat.PNG, 100, streamCamera);
byte[] byteArrayCamera = streamCamera.toByteArray();
InputStream isCamera = new ByteArrayInputStream(byteArrayCamera);
uploadPicture(isCamera);
break;
case PICKER_GALLERY:
Log.d("Profile", "PICKER_GALLERY");
Uri imageUri = data.getData();
try {
Bitmap bitmapGallery = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
Bitmap thumbnailGallery = ThumbnailUtils.extractThumbnail(bitmapGallery, 320, 320);
ByteArrayOutputStream streamGallery = new ByteArrayOutputStream();
thumbnailGallery.compress(Bitmap.CompressFormat.PNG, 100, streamGallery);
byte[] byteArrayGallery = streamGallery.toByteArray();
InputStream isGallery = new ByteArrayInputStream(byteArrayGallery);
uploadPicture(isGallery);
} catch(IOException e) {
e.printStackTrace();
}
break;
default:
Log.d("Profile", "Unmanaged request code: " + requestCode);
break;
}
}
}
public void uploadPicture(InputStream is) {
final ProgressDialog progress = new ProgressDialog(getActivity());
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setTitle(getString(R.string.loading));
progress.setMessage(getString(R.string.loading_msg));
progress.show();
/* Upload*/
AppDelegate appDelegate = (AppDelegate) getActivity().getApplication();
appDelegate.setPicture(is, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload ok");
progress.dismiss();
return null;
}
}, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload failed");
progress.dismiss();
return null;
}
});
}
public void setPictureFile(final InputStream is) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(IOUtils.toByteArray(is));
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
BufferedInputStream buf = new BufferedInputStream(inputStream);
bitmap = BitmapFactory.decodeStream(buf);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
if (inputStream != null) {
inputStream.close();
}
if (buf != null) {
buf.close();
}
} catch(FileNotFoundException e) {
Log.d("Profile", "Picture FILE not found.");
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
Log.d("Profile", "Out Of Memory");
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
In console I always have:
WARNING: bitmap == null
The InputStream in the setPictureFile method is not null (upload to a web-services works as expected) and I didn't get any exception in setPictureFile.
On the other hand, when I'm trying to read the file, the bitmap seems to be null, no exception is rising up!
The file I'm trying to read is about 200-300 KB, so it's not big, I'm not running out of memory.
Anyone knows what's going on?
Solved. Using byte[] instead of InputStream everywhere, solved my issue.
public void setPictureFile(final byte[] buffer) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(buffer);
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
Log.d("Profile", e.toString());
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
// http://stackoverflow.com/questions/11182714/bitmapfactory-example
// http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
byte[] reader = new byte[inputStream.available()];
if (inputStream.read(reader)!=-1) {
Log.d("Profile", "Reading from stream...");
}
Log.d("Profile", "Stream length: " + reader.length);
bitmap = BitmapFactory.decodeByteArray(reader, 0, reader.length);
//BufferedInputStream buf = new BufferedInputStream(inputStream);
//bitmap = BitmapFactory.decodeStream(inputStream);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
inputStream.close();
//if (buf != null) {
// buf.close();
//}
} catch(FileNotFoundException e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
} catch (OutOfMemoryError e) {
Log.d("Profile Exception", e.toString());
} catch(Exception e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
}
return bitmap;
}
i am using this method to get images from url and i am downloading more than one image the varable below called "name" is an array of names of the images .i want to be able to store all images whos name is in the array thats why i kept the url like that.it seems to work well but i have having problem selecting only one picture out or them.
this is the code to save images
String fileName="code";
try {
URL url = new URL("http://10.0.2.2/picure/"+name+".jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
byte[] byteArray = outstream.toByteArray();
fos.write(byteArray);
fos.close();
Toast.makeText(getActivity()," connected", Toast.LENGTH_LONG).show();
} catch(Exception e) {
}
this is the code to collect images
String path = mContext.getFilesDir().toString();
String fileName = "code";
if (fileName != null && !fileName.equals("")) {
Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
if (bMap != null) {
category_logo.setImageBitmap(bMap);
}
}
i know the names of the images i saved so how do i select that one specifically
For get all images use a Asynctask, this code can download images in cache directory of the app:
class ImageDownloader extends AsyncTask<String, Void, File> {
String imageurl;
String name;
Context ctx;
public ImageDownloader(Context context, String url, String fileName) {
this.imageurl = url;
this.name = fileName;
this.ctx = context;
}
#Override
protected File doInBackground(String... urls) {
Bitmap mIcon;
File cacheDir = ctx.getCacheDir();
File f = new File(cacheDir, name);
try {
InputStream in = new java.net.URL(imageurl).openStream();
mIcon = BitmapFactory.decodeStream(in);
try {
FileOutputStream out = new FileOutputStream(
f);
mIcon.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
return f;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
Toast.makeText(ctx," connected " + name, Toast.LENGTH_LONG).show();
}
}
}
For call the asynctask, you need use a FOR for get all names and url of the image:
new ImageDownloader(getBaseContext(),url[i],name[i]).execute();
You can edit the doInBackground with your code, but the HTTPConnection that you use is deprecated in API 22, please use the example above, you can change the directory.
And sorry for the code, you can reformat later.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_MULTIPLE_IMG_GALLERY && resultCode==RESULT_OK){
ClipData clipData = data.getClipData();
if (clipData!=null){
File folderPath = new File(getIntent().getStringExtra("folderpath"));
for (int i = 0;i< clipData.getItemCount();i++){
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
Bitmap selectedImage = loadFromUri(uri);
File imagePath = new File(folderPath,System.currentTimeMillis()+".jpg");
try {
outputStream = new FileOutputStream(imagePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
selectedImage.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
Log.d("uri",uri.toString());
imageModelList.add(new ImageModel(uri.toString()));
}
imagesAdapter.notifyDataSetChanged();
Toast.makeText(ImageDetailActivity.this, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
}
public Bitmap loadFromUri(Uri photoUri) {
Bitmap image = null;
try {
// check version of Android on device
if(Build.VERSION.SDK_INT > 27){
// on newer versions of Android, use the new decodeBitmap method
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), photoUri);
image = ImageDecoder.decodeBitmap(source);
} else {
// support older versions of Android by using getBitmap
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
}
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
I develop an Android App and I develop a feature to take a picture from the gallery and to send it to my server and assign it to user as his profil picture.
I select an image (important : taken by ma camera) and I convert it to base64 before sending it to my server. When I get the image and I try to display it I have only part of the picture but not for image in png... I tried to change compressformat in JPEG and it's worst... I didn't understand the problem since 2 days I get crazy... Help Please :)
private Bitmap bitmap;
public void chooseProfilePicture(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null)
bitmap.recycle(); // recyle unused bitmaps
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
imageView.setImageBitmap(bitmap);
// HERE THE IMAGE IS DISPLAYED 100% WELL
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (Exception ex) {
Log.e("EditProfilActivity", ex.getMessage());
}
}
}
public void save(View view) {
if (bitmap != null) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
bitmap.recycle();
byte[] imageBytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
picture = encodedImage;
// HERE WHEN I TRY TO DISPLAY THE IMAGE I HAVE ONLY A PART OF THE IMAGE
} catch (Exception e) {
Log.e("", e.getMessage());
}
}
You are trying to show image form string(from encoding image file)?
byte[] imagebyteArry = byteArrayOutputStream.toByteArray();
String imageString = encodeImage(imagebyteArry);
sendImageToserver(imageString);
............
String imageString = getImageFromserver();
byte[] imagebyteArry = decodeImage(imageString);
Search how to show image from byte[] in android?
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
I am trying to take the output of the captured image into a uri but it throws null pointer exception on another component which was not null before and when not storing the image in uri it runs okay
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"Photo" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap temp=null;
Bundle extras = data.getExtras();
/*Uri g=data.getData();
try {
temp = MediaStore.Images.Media.getBitmap(getContentResolver(), g);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
int h=photo.getHeight();
int w=photo.getWidth();
/* try {
temp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri1);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmapdata = stream.toByteArray();
Log.i("image", ""+bitmapdata);
image_boolean=true;
stream.flush();
stream.close();
/*File f = new File(mImageCaptureUri1.getPath());
if (f.exists()) f.delete();*/
}catch(Exception e)
{}
imageView.setImageBitmap(photo);
}}
}