Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm making a wallpaper application. In this full-screen image activity, this activity is getting data from previous activity by intent. Now I want to set the image(that comes from URL) as wallpaper. This code is not working.
public class PhotoFullPopupWindow extends AppCompatActivity {
Activity context;
Bitmap bitmap=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_screen_image_view);
ImageView fullScreenImageView = findViewById(R.id.FullScreenImageView);
final String url=getIntent().getStringExtra("url");
Glide.with(this)
.load(url)
.into(fullScreenImageView);
context=this;
bitmap = getBitmap(url);
Button setWallpaperButton = findViewById(R.id.setWallpaper);
setWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL URL = new URL(bitmapUrl);
return BitmapFactory.decodeStream(URL.openConnection().getInputStream());
}
catch(Exception ex) {
return null;
}
}
}
below is the code i used for setting the wallpaper
public void setWallpaper(String url) {
WallpaperManager myWallManager = WallpaperManager.getInstance(getApplicationContext());
Glide.with(this)
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(getLocalBitmapUri(resource), "image/*");
intent.putExtra("jpg", "image/*");
startActivity(Intent.createChooser(
intent, "Set as:"));
}
private Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"OP_Wallpaper_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Try this:
In your first activity, you should save the Bitmap to disk.
Then load it up in the next activity.
Make sure to recycle your bitmap in the first activity to prime it for garbage collection.
In Activity 1:
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
In Activity 2:
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Related
Save Image from ImageView in android Not Working. Image loading By Volley from JSON . I want to save that image in Gallery but on some devices this code not working.
BitmapDrawable draw = (BitmapDrawable) thumbnail.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File dir = new File(Environment.getExternalStorageDirectory() + "");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JobsDetail.this, "Download Successfully", Toas.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
Simply use this to download directly from Image Url
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
progressBar.setVisibility(View.GONE);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
LicenseFrontFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Set the bitmap into ImageView
//image.setImageBitmap(result);
// Close progressdialog
}
To use , call this way
new DownloadImage().execute(image_url);
Add write permissions in manifest also
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And runtime persmissions for Marshmallow or above devices
Create a class SaveImageHelper code is below
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> mDialog;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context,AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.mDialog = new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference = new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog dialog = mDialog.get();
if(r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
dialog.dismiss();
Toast.makeText(context, "Image Download Successfully...", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
//Intent intent = new Intent();
//intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// context.startActivity(Intent.createChooser(intent,"SELECT PICTURE"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
and Use it in another class / Activity by button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ActivityCompat.checkSelfPermission(JobsDetail.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(JobsDetail.this, "You Should Grant Permission..", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}
return;
}
else{
AlertDialog dialog = new SpotsDialog(JobsDetail.this);
dialog.show();
dialog.setMessage("Downloading....");
String filename = UUID.randomUUID().toString()+".jpg";
Picasso.with(getBaseContext())
.load(imageUrl)
.into(new SaveImageHelper(getBaseContext(),
dialog, getApplicationContext().getContentResolver(),
filename,"Image Descp"));
}
Also set Permission in oncreate to access files and images in device
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}
I know there is lots of question regarding the same problem and i have tried many solution like this but i am still getting the empty string.
here is my code
try {
URL url = new URL(myUrl);
InputStream in = url.openConnection().getInputStream();
BufferedInputStream bis = new BufferedInputStream(in,1024*8);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
bis.close();
byte[] data = out.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
d = new BitmapDrawable(getResources(), bmp);
} catch (FileNotFoundException e) {
d = getResources().getDrawable(R.mipmap.background);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myUrl is firebase storage url
Add Picassso libarary in your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
Than download image using picasso like this :
Picasso.with(this)
.load(myUrl)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//Convert your drawable here
d = new BitmapDrawable(getResources(), bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.
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;
}
First off i am writing a root app so root permissions are no issue. I've searched and searched and found a lot of code that never worked for me here is what i've pieced together so far and sorta works. When i say sorta i mean it makes an image on my /sdcard/test.png however the file is 0 bytes and obviously can't be viewed.
public class ScreenShot extends Activity{
View content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
content = findViewById(R.id.blankview);
getScreen();
}
private void getScreen(){
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Any help on how i can take a screen shot in android via code would be greatly appreciated thank you!
===EDIT===
The following is everything i'm using the image is made on my sdcard and is no longer 0bytes but the entire thing is black there is nothing on it. I've bound the activity to my search button so when i'm some where on my phone i long press search and it is supposed to take a screen shot but i just get a black image? Everything is set transparent so i'd think it should grab whatever is on the screen but i just keep getting black
Manifest
<activity android:name=".extras.ScreenShot"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.SEARCH_LONG_PRESS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
android:id="#+id/screenRoot">
</LinearLayout>
Screenshot class
public class ScreenShot extends Activity{
View content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenshot);
content = findViewById(R.id.screenRoot);
ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScreen();
}
});
}
private void getScreen(){
View view = content;
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "test.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
Here you go...I used this:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, getString(R.string.free_tiket)+".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage( getContentResolver(), b,
"Screen", "screen");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
v iz root layout...just to point ;)))
For the next reader of this question-
The very simple way to do this by drawing your view to canvas-
pass your main layout reference to this method-
Bitmap file = save(layout);
Bitmap save(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
I think you have to wait until the layout is drawn completely..Use ViewTreeObserver to get a call back when layout is drawn completely..
On your onCreate add this code..Only call getScreen from inside onGlobalLayout()..
ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScreen();
}
});
I asked a somewhat similiar question once..Please see my question which explains the way to take screenshot in android..Hope this helps
public class MainActivity extends Activity
{
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
}
public Bitmap takeScreenshot()
{
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap)
{
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try
{
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e)
{
Log.e("GREC", e.getMessage(), e);
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}
}
don't forgot to give write external storage permission!
You Take Screen Shot Like this........
View view = findViewById(R.id.rellayout);
view.getRootView();
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File picDir = new File(Environment.getExternalStorageDirectory()+ "/name");
if (!picDir.exists())
{
picDir.mkdir();
}
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap bitmap = view.getDrawingCache();
// Date date = new Date();
String fileName = "mylove" + ".jpg";
File picFile = new File(picDir + "/" + fileName);
try
{
picFile.createNewFile();
FileOutputStream picOut = new FileOutputStream(picFile);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), (int)(bitmap.getHeight()/1.2));//Optional
boolean saved = bitmap.compress(CompressFormat.JPEG, 100, picOut);
if (saved)
{
Toast.makeText(getApplicationContext(), "Image saved to your device Pictures "+ "directory!", Toast.LENGTH_SHORT).show();
} else
{
//Error
}
picOut.close();
}
catch (Exception e)
{
e.printStackTrace();
}
view.destroyDrawingCache();
} else {
}