How to make a screenshot from the Microsoft Surface emulator? - pixelsense

In order to write a user manual for my application, I need to take some screenshots from the Microsoft Surface emulator.
How can I do that? For sure I could just make a screenshot in my OS and then cut the image in a photo editor, but isn't there a simpler way?

So finally I found a nice way to do it:
class ScreenshotTaker
{
public static void TakeScreenshot(Visual target)
{
String fileName = "Screenshot-" + DateTime.UtcNow.ToString().Replace(" ", "-").Replace(".", "_").Replace(":", "_") + ".tiff";
Console.WriteLine("Try to take screenshot: " + fileName);
FileStream stream = new FileStream(fileName, FileMode.Create);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(GetScreenShot(target)));
encoder.Save(stream);
stream.Flush();
stream.Close();
Console.WriteLine("Screenshot taken");
}
private static BitmapSource GetScreenShot(Visual target)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap bitmap = new RenderTargetBitmap(1024, 768, 96, 96, PixelFormats.Pbgra32);
DrawingVisual drawingvisual = new DrawingVisual();
using (DrawingContext context = drawingvisual.RenderOpen())
{
context.DrawRectangle(new VisualBrush(target), null, new Rect(new Point(), bounds.Size));
context.Close();
}
bitmap.Render(drawingvisual);
return bitmap;
}
}

Related

How to set image.Source via async stream in an UWP application?

I want to set image.Source via async stream in an UWP application. Otherwise the image will flicker when switch to other image source.
My code is as below. And the log shows it works. Certainly I put 2 image files in the corresponding path before I test the demo code.
But in fact I did not see any picture shown, why?
Log:
111111111111 image file path = C:\Users\tomxu\AppData\Local\Packages\a0ca0192-f41a-43ca-a3eb-f128a29b00c6_1qkk468v8nmy0\LocalState\2.jpg
22222222222
33333333333333
4444444444444
The thread 0x6d38 has exited with code 0 (0x0).
The thread 0x6a34 has exited with code 0 (0x0).
111111111111 image file path = C:\Users\tomxu\AppData\Local\Packages\a0ca0192-f41a-43ca-a3eb-f128a29b00c6_1qkk468v8nmy0\LocalState\1.jpg
22222222222
33333333333333
4444444444444
Code:
private async void setImageSource(string imageFilePath)
{
StorageFile sFile = await StorageFile.GetFileFromPathAsync(imageFilePath);
Debug.WriteLine("111111111111 image file path = " + imageFilePath);
Stream fileStream = await sFile.OpenStreamForReadAsync();
Debug.WriteLine("22222222222");
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
Debug.WriteLine("33333333333333");
await fileStream.CopyToAsync(ras.AsStreamForRead());
Debug.WriteLine("4444444444444");
BitmapImage bi = new BitmapImage();
bi.SetSource(ras);
image1.Source = bi;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string fullFolder = ApplicationData.Current.LocalFolder.Path;
if (count % 2 == 1)
{
setImageSource(fullFolder + #"\1.jpg");
//image1.Source = new BitmapImage(new Uri(#"ms-appx:///Assets/1.jpg"));
}
else
{
setImageSource(fullFolder + #"\2.jpg");
//image1.Source = new BitmapImage(new Uri(#"ms-appx:///Assets/2.jpg"));
}
count++;
}
Here is an example of how I convert a base64 image string to a BitmapImage..
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(base64String);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
ims.Dispose();
return img;
Try some of the things I'm doing there. Like I notice your code is not setting the seek of the InMemoryReadAccessStream
For your question, I have something to clarify with you.
Your pictures are always in the application data folder. If you want to show it at runtime by programming, the easy way is using the ms-appdata URI scheme to refer to files that come from the app's local, roaming, and temporary data folders. Then, you could use this URL to initialize the BitmapImage object. With this way, you don't need to manually manipulate the file stream.
private void setImageSource(int i)
{
BitmapImage bi = new BitmapImage(new Uri("ms-appdata:///local/"+i+".png"));
image1.Source = bi;
}
private int count = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
if (count % 2 == 1)
{
setImageSource(1);
}
else
{
setImageSource(2);
}
count++;
}
If you say you have to manipulate the file stream to initialize the BitmaImage, then please add some break points to debug your code. If you add break points to check the InMemoryRandomAccessStream after call CopyToAsync method, you will see that its size is 0. It meant that the file stream has not been wrote to it. To solve this issue, you need to set a buffer size for it. Note: you used ras.AsStreamForRead() method, it's incorrect. You're writing stream to it, so you need to call ras.AsStreamForWrite().
The code looks like the following:
private async void setImageSource(string imageFilePath)
{
StorageFile sFile = await StorageFile.GetFileFromPathAsync(imageFilePath);
using (Stream fileStream = await sFile.OpenStreamForReadAsync())
{
using (InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream())
{
await fileStream.CopyToAsync(ras.AsStreamForWrite((int)fileStream.Length));
ras.Seek(0);
BitmapImage bi = new BitmapImage();
bi.SetSource(ras);
img.Source = bi;
}
}
}
private int count = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
string fullFolder = ApplicationData.Current.LocalFolder.Path;
if (count % 2 == 1)
{
setImageSource(fullFolder + #"\1.jpg");
}
else
{
setImageSource(fullFolder + #"\2.jpg");
}
count++;
}
In addition, like #visc said, you need to call ras.Seek(0) method to reset the stream to beginning, else the image will not show there.

Android N FileUriExposedException

Guys My app uses the stock camera to take a picture I use the following code to take a picture
public void takepic(View view) {
TextView schtitle = (TextView) findViewById(R.id.Sitename);
String schname = schtitle.getText().toString();
String[] tokens = schname.split(" ");
String timeStamp = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date());
String imageFileName = tokens[0] + "-" + timeStamp + ".jpg";
TextView myAwesomeTextView = (TextView)findViewById(R.id.filetext);
//in your OnCreate() method
myAwesomeTextView.setText(imageFileName);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String name = imageFileName;
File file = new File(path, name );
outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
This works fine in all but Nougat
I understand as they did in marshmallow you now need permissions and cant use file URI anymore
I cant find any sample code on how to take a picture in nougat could someone please point me in the right direction as to how I modify my code to allow this to happen?
Any help appreciated
Mark
The problem is the file:// uri is not permited anymore.
Instead of this you must use FileProvider.
Take a look here: https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en
Just quoting this here for reference.
We now have an updated documentation on how to use camera intent with a file uri to store the taken picture under the training section of android.
https://developer.android.com/training/camera/photobasics.html
public void openShare(View view) {
// save bitmap to cache directory
try {
bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
File cachePath = new File(getCacheDir(), "images");
if (!cachePath.exists())
cachePath.mkdirs();
FileOutputStream stream = new FileOutputStream(cachePath + "/" + imageName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
shareImage();
} catch (Exception e) {
e.printStackTrace();
}
}
private void shareImage() {
File imagePath = new File(getCacheDir(), "images");
File newFile = new File(imagePath, imageName);
Uri contentUri = MyFileProvider.getUriForFile(this, "com.example.kushaalsingla.contentsharingdemo", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri, getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(shareIntent, "Choose an app"));
}
}
################## Add in Manifest
<provider
android:name=".MyFileProvider"
android:authorities="com.example.kushaalsingla.contentsharingdemo"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
################## filepaths.xml ########################
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="shared_images" path="images/"/>
</paths>

How to remove one indirectly referenced image from a PDF and keep all others?

I would like to parse a PDF and find the logo via known attributes and when I find a match, remove that image and then copy everything else.
I am using the code below to replace an image with a blank white image to remove a logo from PDFs that are to be printed on letterhead. It replaces the image with a white image of the same size. Is there a way to modify this to actually remove the image (and thus save some space, etc.?).
private static void Main(string[] args)
{
ManipulatePdf(#"C:\in.pdf", #"C:\out.pdf");
Console.WriteLine("Finished - press a key");
Console.ReadKey();
}
public static void ManipulatePdf(String src, String dest)
{
Console.WriteLine("Start");
PdfReader reader = new PdfReader(src);
// first read all references and find the one we wish to work on.
PdfDictionary page = reader.GetPageN(1); // all resources are available to every page (?)
PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);
PdfDictionary xobjects = resources.GetAsDict(PdfName.XOBJECT);
page = reader.GetPageN(1);
resources = page.GetAsDict(PdfName.RESOURCES);
xobjects = resources.GetAsDict(PdfName.XOBJECT);
foreach (PdfName pdfName in xobjects.Keys)
{
PRStream stream = (PRStream) xobjects.GetAsStream(pdfName);
if (stream.Length > 100000)
{
PdfImage image = new PdfImage(MakeBlankImg(), "", null);
Console.WriteLine("Calling replace stream");
ReplaceStream(stream, image);
}
}
PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
stamper.Close();
reader.Close();
}
public static iTextSharp.text.Image MakeBlankImg()
{
Console.WriteLine("Making small blank image");
byte[] array;
using (MemoryStream ms = new MemoryStream())
{
//var drawingImage = image.GetDrawingImage();
using (Bitmap newBi = new Bitmap(1, 1))
{
using (Graphics g = Graphics.FromImage(newBi))
{
g.Clear(Color.White);
g.Flush();
}
newBi.Save(ms, ImageFormat.Jpeg);
}
array = ms.ToArray();
}
Console.WriteLine("Image array is " + array.Length + " bytes.");
return iTextSharp.text.Image.GetInstance(array);
}
public static void ReplaceStream(PRStream orig, PdfStream stream)
{
orig.Clear();
MemoryStream ms = new MemoryStream();
stream.WriteContent(ms);
orig.SetData(ms.ToArray(), false);
Console.WriteLine("Iterating keys");
foreach (KeyValuePair<PdfName, PdfObject> keyValuePair in stream)
{
Console.WriteLine("Key: " + keyValuePair.Key.ToString());
orig.Put(keyValuePair.Key, stream.Get(keyValuePair.Key));
}
}
}

Pdf file is not viewing in android app

Anyone can help in this code, the pdf file is not loading in app and just showing blank white screen, Logcat showing FileNotFoundExeeption: /storage/sdcard/raw/ourpdf.pdf.
i am trying to make an app that will show information while i click buttons and every button will be active for specific pdf file reading. Any specific help please.
Thanks for help
part1
package com.code.androidpdf;
public class MainActivity extends Activity {
//Globals:
private WebView wv;
private int ViewSize = 0;
//OnCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Settings
PDFImage.sShowImages = true; // show images
PDFPaint.s_doAntiAlias = true; // make text smooth
HardReference.sKeepCaches = true; // save images in cache
//Setup above
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
wv.getSettings().setSupportZoom(true);//allow zoom
//get the width of the webview
wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
ViewSize = wv.getWidth();
wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
pdfLoadImages();//load images
}
private void pdfLoadImages() {
try
{
// run async
new AsyncTask<Void, Void, Void>()
{
// create and show a progress dialog
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "", "Opening...");
#Override
protected void onPostExecute(Void result)
{
//after async close progress dialog
progressDialog.dismiss();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
// select a document and get bytes
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/randompdf.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
net.sf.andpdf.nio.ByteBuffer bb = null ;
raf.close();
// create a pdf doc
PDFFile pdf = new PDFFile(bb);
//Get the first page from the pdf doc
PDFPage PDFpage = pdf.getPage(1, true);
//create a scaling value according to the WebView Width
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
//convert the page into a bitmap with a scaling value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
//save the bitmap to a byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byte[] byteArray = stream.toByteArray();
//convert the byte array to a base64 string
String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
//create the html + add the first image to the html
String html = "<!DOCTYPE html><html><body bgcolor=\"#7f7f7f\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
//loop through the rest of the pages and repeat the above
for(int i = 2; i <= pdf.getNumPages(); i++)
{
PDFpage = pdf.getPage(i, true);
page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
byteArray = stream.toByteArray();
base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
}
html += "</body></html>";
//load the html in the webview
wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");
}
catch (Exception e)
{
Log.d("CounterA", e.toString());
}
return null;
}
}.execute();
System.gc();// run GC
}
catch (Exception e)
{
Log.d("error", e.toString());
}
}
}
It is (sadly) not possible to view a PDF that is stored locally in your devices. Android L has introduced the feature. So, to display a PDF , you have two options:
See this answer for using webview
How to open local pdf file in webview in android? (note that this requires an internet connection)
Use a third party pdf Viewer.
You can also send an intent for other apps to handle your pdf.
You can get an InputStream for the file using
getResources().openRawResource(R.raw.ourpdf)
Docs: http://developer.android.com/reference/android/content/res/Resources.html#openRawResource(int)

Screenshot does not take the latest, current or updated view (Android)

I'm trying to switch a banner adView to imageView just before I take a screenshot so that users can share this screenshot through share intent.
However, when I take the screenshot, it does not include the imageView.
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
adView1 = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID1);
LinearLayout.LayoutParams childParam2 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0.10f);
adView1.setLayoutParams(childParam2);
adView1.loadAd(new AdRequest());
ll.addView(adView1);
setContentView(ll);
myAdView = new ImageView(this);
LinearLayout.LayoutParams childParam1 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0.10f);
myAdView.setLayoutParams(childParam1);
....
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
...
case R.id.menu3:
share();
break;
...
}
}
Here's share() function.
private void share(){
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
List<ResolveInfo> resInfo =
this.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
........
if (packageName.toLowerCase().contains("twitter")){
targetedShareIntent.setType("*/*");
String location = "file://" + takeScreen(ll);
...
}
...
}
This is takeScreen(View v) function.
public String takeScreen(View c_view){
ll.removeView(adView1);
ll.addView(myAdView);
// create bitmap screen capture
Bitmap bitmap;
View v1 = c_view.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = v1.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File imageFile = new File(extr, "screen_" + System.currentTimeMillis() + ".jpg");
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
//Log.e("bitmap saved ?", saved + "!");
fout.flush();
fout.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ll.removeView(myAdView);
ll.addView(adView1);
return imageFile.getPath();
}
As you can see, I'm removing adView and adding myAdView(imageView) just before the screenshot is taken in takeScreen() function. adView IS removed but imageVies is NOT added to the screenshot.
The imageView DOES appear on the screen just before chooserIntent(share intent) pop-up screen is displayed.
I have tried many other options like
added both views and just switched visibility. setVisibility(View.Gone, View.Visible)
tried creating bitmap with canvas instead of getDrawingCache (thinking that it could be a cache related problem)
Is taking screenshot or 'share intent' too much of work for the UI thread to be blocked?
Can anyone shed a light here? I am completely at a loss.
I found a way to get around this. I created a composite bitmap out of the background bitmap and the overlay(my ad image) bitmap. In case anyone is interested, here's the code.
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
Bitmap overlay = BitmapFactory.decodeResource(this.getResources() , R.drawable.my_ad);
canvas.drawBitmap(overlay, 100, 100, null);
return bitmap;
}