I have Image view list in adapter on click of image I show full screen image. Where I have one button outside of adapter in fragment.
Now I want to get that image in fragment onClick of button to share that image.
Below code this in adapter where my images are getting download.
I have using Android-Universal-Image-Loader library to show images.
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(callback != null) {
Bitmap bitmap = ((BitmapDrawable) img_main_bg.getDrawable()).getBitmap();
callback.onItemClicked(bitmap);
}
spinner.setVisibility(View.GONE);
}
How do I get image in fragment?
I already tried interface but onLoadingComplete downloading multiple image at time so I can't get right image on that.
you can do it following way
first make click listener in that ask for permission to save image
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
imgView = imageView;
boolean hasPermission = (ContextCompat.checkSelfPermission(ImagePagerActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(ImagePagerActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
112);
}else
{
showDialog();
}
}
});
if permission is applied then save image first then share it
private void showDialog()
{
new AlertDialog.Builder(ImagePagerActivity.this,R.style.MyAlertDialogStyle)
.setTitle("Select your option")
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
try {
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ "Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root,
System.currentTimeMillis()
+ ".jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(
ImagePagerActivity.this,
"File saved at Beauty folder",
Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(
ImagePagerActivity.this,
"Error occured. Please try again later.",
Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
}
})
.setNegativeButton("Share",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
try {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ " Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root, "1.jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Intent shareIntent = new Intent(
Intent.ACTION_SEND);
Uri phototUri = Uri
.fromFile(sdImageMainDirectory);
shareIntent.setData(phototUri);
shareIntent
.setType("image/png");
shareIntent.putExtra(
Intent.EXTRA_STREAM,
phototUri);
startActivityForResult(Intent
.createChooser(
shareIntent,
"share using"),
2);
} catch (Exception ce) {
ce.printStackTrace();
}
}
})
.show();
}
Related
How to handle full-sized photo using MediaStore.EXTRA_OUTPUT? First, I need to put the picture AS FULL-SIZED NOT THUMBNAIL on a layout and put text below it like this:
The idea I am using is that I am using layout.getDrawingCache to make it as bitmap.
Below is my camera button:
private void SelectImage(){
final CharSequence[] items={"Camera", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PickupDrop.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!= null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (Exception e) {
e.printStackTrace();
}
if(imageFile!= null){
imageUri =FileProvider.getUriForFile(context, "com.example.android.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent,REQUEST_CAMERA);
}
}
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
The getImageFile() method:
private File getImageFile(){
String imageName = "test";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
currentImagePath = imageFile.getAbsolutePath();
return imageFile;
}
As you can see above, I am using EXTRA_OUTPUT with fileprovider to get FULL-SIZED bitmap.
Below is my manifests, provider.
Manifest:
<application ...
<provider
android:authorities="com.example.android.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"/>
</provider>
file_path.xml:
<?xml version="1.0" encoding="utf-8"?>
<external-path
name="my images"
path="Android/data/com.example.luckypasabayapp/files/Pictures"/>
My onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
populateScreenshot(bitmap);
}
}
}
Now here is where my problem occurs when I try to save the relative layout screenshot to my storage:
public void populateScreenshot(Bitmap bitmapFromPhone){
LayoutInflater inflater = LayoutInflater.from(PickupDrop.this);
View v = inflater.inflate(R.layout.information_dialog, null);
ImageView imageView_profilePic = v.findViewById(R.id.imageview_image);
TextView txt_item_data = v.findViewById(R.id.txt_item_data);
Button btn_cancel = v.findViewById(R.id.btn_cancel);
Button btn_download = v.findViewById(R.id.btn_download);
screenShot = v.findViewById(R.id.screenShot);
screenShot.setDrawingCacheEnabled(true);
screenShot.buildDrawingCache();
final AlertDialog alertDialog = new AlertDialog.Builder(PickupDrop.this)
.setView(v)
.create();
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Prevent dialog close on back press button
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
//alertDialog.setCanceledOnTouchOutside(false);
//SETTING THE IMAGEVIEW OF LAYOUT TAKEN FROM CAMERA
imageView_profilePic.setImageBitmap(bitmapFromPhone);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//GETTING THE RELATIVELAYOUT AS BITMAP
Bitmap bitmap = screenShot.getDrawingCache();
File filePath = Environment.getExternalStorageDirectory();
File dir = new File(filePath.getAbsolutePath()+"/qrcode/");
dir.mkdirs();
File file = new File(dir, "str_specialNumber" + ".png");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//HERE IS WHERE THE ERROR OCCURS, IT SAYS BITMAP IS NULL!!!
bitmap.setHasAlpha(true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,outputStream);
Toast.makeText(PickupDrop.this,"SCREENSHOT Downloaded",Toast.LENGTH_LONG).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//notify gallery for a new picture
galleryAddPic(filePath.getAbsolutePath()+"/qrcode/"+"str_specialNumber"+".png");
}
});
alertDialog.show();
}
Here in bitmap.setHasAlpha(true); it says bitmap is null from screenshot.getDrawingCache I don't understand why.
How do I handle the EXTRA_OUTPUT properly to be able to do whatever I want with the bitmap?
You can give this answer a try :)
If you want to take the screenshot of any view or your RelativeLayout you can create this method takeScreenShot() : it will return a Bitmap
in #Param or parameter in this method, you can pass RelativeLayout
public static Bitmap takeScreenShot(#NonNull View view) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
view.buildDrawingCache();
if (view.getDrawingCache() == null) return null;
Bitmap snapshot;
try {
snapshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
} catch (Exception e) {
snapshot = null;
}
return snapshot;
}
tell me if this helps you :)
This contents of this loadImage method never gets called although I am calling this method in OnActivityResult.
public void loadImage(Uri uri){
File file = new File(getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/" +uid + ".jpg");
Log.d("Check Bitmap", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Check Bitmap", "bitmap working");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
} catch (Exception e) {
Log.d("Check Bitmap", "bitmap not working, cached");
e.printStackTrace();
}
My aim is to retrieve the image from the file.
This is my OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==1000){
{
if(resultCode == Activity.RESULT_OK){
imageUri = data.getData();
Context context;
final ProgressDialog dialog = new ProgressDialog(myProfile.this);
dialog.setMessage("Uploading Image...");
dialog.show();
profilepic.setImageURI(imageUri);
ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(uri).into(profilepic);
downloadUri = uri;
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded!", Toast.LENGTH_SHORT).show();
loadImage(uri); //Here I call
You should not use space separated TAG for logs. Try replacing your "Check Bitmap" with something of one word (eg. "Checkere"). Then you will be able to see your Log in your Logcat.
You need to put everything inside a thread.
Here is the complete block of code for loadImage
public void loadImage(final Uri uri){
Thread thread = new Thread() {
#Override
public void run() {
Log.d("Checkere", "stuck at file");
File file = new File(getCacheDir() + File.separator + uid + ".jpg");
Log.d("Checkere", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Checkere", "bitmap working");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
Log.d("Checkere", e.getMessage());
e.printStackTrace();
}
}};
thread.start();
}
Note that I have also added these two lines in your code.
fOut.flush();
fOut.close();
I hope this helps!
I am implementing a button which lets you take a screenshot, but I want to save it on the Android Internal Storage not in the External Storage (SD Card).
I tried this:
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 {
fos.close();
}
return directory.getAbsolutePath();
}
I've started this method with an OnClick method of a button:
private void takeScreenshot(View v) {
v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
saveToInternalStorage(bitmap)
}
But this didn't work. Instead, when I click the button, an error message appears on my cell phone: "Application has stopped".
Hope you can help me.
I think you need to use openFileOutput to get a FileOutputStream, try following the example in the doc https://developer.android.com/training/basics/data-storage/files.html
What's the error in the logcat?
/**
* This function captures any Android views to a bitmap shapshot
* and save it to a file path
* and optionally open it with android pciture viewer
*/
public void CaptureView(View view, String filePath, boolean bOpen) {
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 95, new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bOpen) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath), "image/*");
startActivity(intent);
}
}
Usage:
File sdcard = Environment.getExternalStorageDirectory();
String path = sdcard + "/demo.jpg";
CaptureView(someViewInstace, path, false);
You can use Context.getFilesDir() method to get the path to the internal storage:
String path = yourActivity.getFilesDir() + "/" + name);
Add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
add this line manifest file application tag
android:requestLegacyExternalStorage="true"
In activity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int permission = ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
MainActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
} else {
takeScreenshot();
}
}
});
}
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(MainActivity.this, "Successfully saved", Toast.LENGTH_SHORT).show();
//**if you want to open this screenshot
openScreenshot(imageFile);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
}
I'm using the universal image loader for my app. I want to save the current image displayed by the ViewPager to the SD-Card however the code I have below is saving the wrong image to the SD-Card. It saves the images at random only. I need to way of knowing how to retrieve the current bitmap of the image and saving it. I don't know any other alternatives of getting the bitmap of the current image and saving it to the SD-Card. The way I'm getting the bitmap currently is through "Bitmap bitmap = loadedImage". Your help would be greatly appreciated. Cheeers.
public class ImagePagerFragment extends BaseFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_pager, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new ImageAdapter());
pager.setCurrentItem(getArguments().getInt(Constants.Extra.IMAGE_POSITION, 0));
return rootView;
}
private class ImageAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
final christ.triumphant.TouchImageView imageView = (christ.triumphant.TouchImageView) imageLayout.findViewById(R.id.imagei);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {
..
#Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
isave = (Button) getView().findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap bitmap = loadedImage;
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
File f = new File(folder, String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Image Successfully Saved", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File ff = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(ff);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
else
{
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ishare = (Button) getView().findViewById(R.id.share);
ishare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap icon = loadedImage;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Toast.makeText(getActivity(), "Image Successfully Shared", Toast.LENGTH_LONG).show();
}
});
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
... ... ... }
I'm creating a android app that has the following purpose:
Save the canvas as image on SD card
Always keep the first picture even after I clean (with ClearPaint button)
Paint a new picture will keep the previous image again
Code:
Button Colorpaint = (Button) findViewById(R.id.color);
Colorpaint.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int _color = R.color.red;
new PickerDialog(v.getContext(),new OnColorChangedListener() {
public void colorChanged(int color) {
mPaint.setColor(color);
Log.i("TAG", "mpaint one" +mPaint);
}
}, mPaint.getColor(), _color).show();
Log.i("TAG", "mpaint two" +mPaint);
}
});
ClearPaint = (Button) findViewById(R.id.ClearPaint);
ClearPaint.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mBitmap.eraseColor(Color.TRANSPARENT);
mPath.reset();
mView.invalidate();
}
});
btn_shoot = (Button)findViewById(R.id.btn_shoot);
btn_shoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = findViewById(R.id.item);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//we check if external storage is available, otherwise display an error message to the user
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Basketball_Coach_Board");
directory.mkdirs();
String filename = "tactics" + i + ".jpg";
File yourFile = new File(directory, filename);
while (yourFile.exists()) {
i++;
filename = "tactics" + i + ".jpg";
yourFile = new File(directory, filename);
}
if (!yourFile.exists()) {
if (directory.canWrite())
{
try {
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Toast.makeText(MainActivity.this, "Tactics saved at /sdcard/Basketball_Coach_Board/tactics" + i + ".jpg", Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else
{
Toast.makeText(MainActivity.this, "SD Card not available!", Toast.LENGTH_SHORT).show();
}
}
});
I guess this is because after successfully taking the picture you don't reset the drawing cache to false with: view.setDrawingCacheEnabled(false);