can someone help me?
I want to take a screenshot and post this to the facebook wall (with a message)!
I have read several topics and forums but i dont find something that worked for me!
I already have the facebook SDK!
Thanks a lot!
capture images of view using this way.
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "yourImageName.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();
}
here v is root layout and than post photo in facebook using SDK 3.5.
like this way
private SimpleFacebook mSimpleFacebook;
mSimpleFacebook = SimpleFacebook.getInstance(this);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
// create Photo instace and add some properties
Photo photo = new Photo(bitmap);
photo.addDescription("Screenshot from sample application");
photo.addPlace("110619208966868");
// publish
mSimpleFacebook.publish(photo, new OnPublishListener()
{
#Override
public void onFail(String reason)
{
mProgress.hide();
// insure that you are logged in before publishing
Log.w(TAG, "Failed to publish");
}
#Override
public void onException(Throwable throwable)
{
mProgress.hide();
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while publishing
mProgress = ProgressDialog.show(this, "Thinking",
"Waiting for Facebook", true);
}
#Override
public void onComplete(String id)
{
mProgress.hide();
toast("Published successfully. The new image id = " + id);
}
});
Related
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();
}
This question already has answers here:
How I can convert a bitmap into PDF format in android [closed]
(3 answers)
Closed 2 months ago.
I am trying to convert an activity to pdf format.I have taken a screenshot of the same as a bitmap.PLease help me to convert that sreenshot to the required pdf file.Thank you.
Please provide the code.Thank you.
This is the code I used...
1) MainActivity
public class MainActivity extends Activity {
//Button btn_getpdf;
private LinearLayout linearLayout;
private Bitmap myBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btn_getpdf = (Button) findViewById(R.id.button_pdf);
linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(linearLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if (myBitmap != null) {
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if (v != null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
} catch (Exception e) {
// Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public void saveImage(Bitmap bitmap) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(root.getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
}
2)WritePdfActivity
public class WritePdfActivity extends Activity
{
private static String FILE ="DCIM/Camera/GenPdf.pdf";
static Image image;
static ImageView img;
Bitmap bmp;
static Bitmap bt;
static byte[] bArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView)findViewById(R.id.imageView1);
try
{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addImage(document);
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void addImage(DocumentsContract.Document document)
{
try
{
image = Image.getInstance(bArray); ///Here i set byte array..you can do bitmap to byte array and set in image...
}
catch (BadElementException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// image.scaleAbsolute(150f, 150f);
try
{
document.add(image);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Plz try this So question:
How I can convert a bitmap into PDF format in android
pdf-format-in-android/14393561#14393561
or also include itextpdf-5.3.2.jar in your project
#Swagatam Dutta use
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
Hello Friends i'm making a app with webview
i want to take screenshot of my activity
Currnetly i'm using this code for capture image
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And This for Save
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);
}
}
It sometime Works and sometime not, i mean ,sometime i can see in gallery screenshot and sometime not
i want to if there is any option to show captured screenshot
Like whhen we press Vol+power button
Main problem is how can i show image when its taken
or know if its taken or not
Thanks in advance
This is a sample approach: save your image -> display result with dialog. And to make it available in Android Gallery, the file path should also be changed:
public void saveBitmap(Bitmap bitmap) {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imagePath = new File(path, "screenshot.png");//now gallery can see it
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
displayResult(imagePath.getAbsolutePath())// here you display your result after saving
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Create another method call displayResult to see the result:
public void displayResult(String imagePath){
//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//ImageView Setup
ImageView imageView = new ImageView(this);//you need control the context of Imageview
//Diaglog setup
final Dialog dialog = new Dialog(this);//you need control the context of this dialog
dialog.setContentView(imageView);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Display result
imageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
dialog.show();
}
Other people have run into issues when trying to get a bitmap from a view's Drawing Cache.
Rather than trying to use the drawing cache, you can instead just get the bitmap directly from the view. Google's DynamicListView example uses the following function to do so.
/** Returns a bitmap showing a screenshot of the view passed in. */
private Bitmap getBitmapFromView(View v) {
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas (bitmap);
v.draw(canvas);
return bitmap;
}
I've been trying different things and I can save a photo in the SD card taken with Camera (not intent) but cannot pick up this same picture from SD card and place it in an ImageView. I get a Null pointer Exception allways.
Don't know what's missing, hope somebody can help me:
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Save the image JPEG data to the SD card
FileOutputStream fos = null;
String fileName = "";
try {
fileName = "/mnt/sdcard/DCIM/MyPicture.jpg";
fos = new FileOutputStream(fileName);
fos.write(data);
fos.close();
Toast.makeText(getBaseContext(), "Image saved:" ,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.e(TAG, "File Note Found", e);
Toast.makeText(getBaseContext(), "Image couldn't be saved.",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
Toast.makeText(getBaseContext(), "Image couldn't be saved.",
Toast.LENGTH_LONG).show();
}
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
Log.d(TAG, fileName);
mImageView.setImageBitmap(bitmap);
}
};
I have tried that too:
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
+ "/DCIM/MyPhoto.jpg");
mImageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
It saves the picture but goes to the catch when trying to put the image in the ImageView saying that "Error reading file"
logcat:
DDMS:
Sorry everybody for the headache... I forgot to put mImageView = (Imageview)findViewById(R.id.imageView1);
I'm a disaster :-)
Try this,
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
Log.v("Path", Environment.getExternalStorageDirectory().getPath()+"/DCIM/MyPhoto.jpg");
mImageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
also check your imageview mImageView initialized or not
Use this. It would help you.
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(CameraPhotoCapture.this);
Bitmap mBitmap;
protected void onPreExecute() {
/****** NOTE: You can call UI Element here. *****/
//UI Element
Dialog.setMessage("Loading image from Sdcard..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
/** Uri.withAppendedPath Method Description
* Parameters
* baseUri Uri to append path segment to
* pathSegment encoded path segment to append
* Returns
* a new Uri based on baseUri with the given segment appended to the path
*/
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, 170, 170, true);
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;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if(mBitmap != null)
showImg.setImageBitmap(mBitmap);
}
}
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 {
}