I am Setting thumbnail of SMTC control from stream via SystemMediaTransportControlsDisplayUpdater, but it is not working
var response = await new HttpClient().GetAsync(imgUrl);
systemMediaTransportControlsDisplayUpdater.Thumbnail = RandomAccessStreamReference.CreateFromStream((await response.Content.ReadAsStreamAsync()).AsRandomAccessStream());
Same is working if i use Url to create random stream.
systemMediaTransportControlsDisplayUpdater.Thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri(imgUrl));
I am merging two images and i want to assign that image as thumbnai to SMTC. To merge images below code i am using.
var response = await httpClient.GetAsync(imgUrl);
var writeableBmp = new WriteableBitmap(1, 1);
var image1 = await writeableBmp.FromStream(await response.Content.ReadAsStreamAsync());
var image2 = await writeableBmp.FromContent(imgUrl1);
image1.Blit(new Rect(0, 0, image1.PixelWidth, image1.PixelHeight), image2, new Rect(0, 0, image2.PixelWidth, image2.PixelHeight));
var randomAccessStream = image1.PixelBuffer.AsStream().AsRandomAccessStream();
systemMediaTransportControlsDisplayUpdater.Thumbnail =
= RandomAccessStreamReference.CreateFromStream(randomAccessStream );
What exactly wrong with merging or setting thumbnail to SMTC?
Thanks
stream via SystemMediaTransportControlsDisplayUpdater, but it is not working
I could reproduce your issue, I will report this, currently there is a workaround that converter WriteableBitmap to StorageFile then pass file argument to RandomAccessStreamReference.CreateFromFile method. You could refer the following code,
private async void MediaPlayer_MediaOpened(MediaPlayer sender, object args)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
var imgUrl = new Uri("https://image.diyidan.net/post/2015/10/27/LILeAOb3BF8qR8Uz.png");
var imgUrl1 = new Uri("ms-appx:///Assets/test.png");
var httpclient = new HttpClient();
var response = await httpclient.GetAsync(imgUrl);
var writeableBmp = new WriteableBitmap(1, 1);
var image1 = await writeableBmp.FromStream(await response.Content.ReadAsStreamAsync());
var image2 = await writeableBmp.FromContent(imgUrl1);
image1.Blit(new Rect(0, 0, image1.PixelWidth, image1.PixelHeight), image2, new Rect(0, 0, image2.PixelWidth, image2.PixelHeight));
var file = await WriteableBitmapToStorageFile(image1, FileFormat.Png);
SystemMediaTransportControlsDisplayUpdater updater = sender.SystemMediaTransportControls.DisplayUpdater;
updater.Thumbnail = RandomAccessStreamReference.CreateFromFile(file);
updater.Update();
});
}
private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
{
string FileName = "YourFile.";
Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
switch (fileFormat)
{
case FileFormat.Jpeg:
FileName += "jpeg";
BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
break;
case FileFormat.Png:
FileName += "png";
BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
break;
case FileFormat.Bmp:
FileName += "bmp";
BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
break;
case FileFormat.Tiff:
FileName += "tiff";
BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
break;
case FileFormat.Gif:
FileName += "gif";
BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
break;
}
var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
Stream pixelStream = WB.PixelBuffer.AsStream();
byte[] pixels = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)WB.PixelWidth, (uint)WB.PixelHeight,
96.0,
96.0,
pixels);
await encoder.FlushAsync();
}
return file;
}
private enum FileFormat
{
Jpeg,
Png,
Bmp,
Tiff,
Gif
}
Related
When I tried to view image in PdfViewer with Letter Format then Image is bluring. while when I tried viewing without defined format then picture is clear.
My Code
private async void Load(PdfDocument pdfDoc)
{
try
{
PdfPages.Clear();
for (uint i = 0; i < pdfDoc.PageCount; i++)
{
BitmapImage image = new BitmapImage();
var page = pdfDoc.GetPage(i);
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
//PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
{
await page.RenderToStreamAsync(stream);
await image.SetSourceAsync(stream);
}
PdfPages.Add(image);
}
}
This Code Belong to Format set
StorageFile ImageFile;
var storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);
StorageFolder projectFolder = await storageFolder.CreateFolderAsync(imageLocation, CreationCollisionOption.OpenIfExists);
StorageFile file = await projectFolder.GetFileAsync(item);
if (file == null) return;
var Stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
IRandomAccessStream stream = await file.OpenReadAsync();
Stream imageStream = stream.AsStreamForRead();
BitmapImage sourceImage = new BitmapImage();
PdfBitmap image = new PdfBitmap(imageStream);
PdfSection section1 = doc.Sections.Add();
section1.PageSettings.Size = PdfPageSize.Letter;
page = section1.Pages.Add();
PdfGraphics graphics = page.Graphics;
//Draw the image
if (fileType == Constants.PrescriptionType.Prescription.GetHashCode())
graphics.DrawImage(image, 0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height);
else
graphics.DrawImage(image, 0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height);
Thank You
I want to save a section of an image taken with a webcam (using Windows.Media.Capture).
Here is what I got so far:
[...]
MediaCapture mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();
await mediaCapture.StartPreviewAsync();
public async void takePhoto(){
var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));
var capturedPhoto = await lowLagCapture.CaptureAsync();
await lowLagCapture.FinishAsync();
await CapturePhotoWithOrientationAsync();
}
private async Task CapturePhotoWithOrientationAsync() {
var captureStream = new InMemoryRandomAccessStream();
try {
await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);
} catch (Exception ex) {
Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
return;
}
var decoder = await BitmapDecoder.CreateAsync(captureStream);
var file = await storageFolder.CreateFileAsync("test.jpeg", CreationCollisionOption.ReplaceExisting);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite)) {
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(Windows.Devices.Sensors.SimpleOrientation.Rotated270DegreesCounterclockwise);
var properties = new BitmapPropertySet {
{ "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
}
}
[...]
This way I can save the whole image. But how can I only save a section of the image?
But how can I only save a section of the image?
With a start point and size you could define a crop bound, and then create a BitmapTransform, with this transform you can get the cropped image pixies by GetPixelDataAsync() method. BitmapEncoder can SetPixelData. Details for how to do please reference How to crop bitmap in a Windows Store app (C#) sample and this tutorial.
For example, based on your code snippet:
//Inside CapturePhotoWithOrientationAsync method
...
Point startPoint = new Point(0, 0);
Size corpSize = new Size(250, 250);
// Convert start point and size to integer.
uint startPointX = (uint)Math.Floor(startPoint.X);
uint startPointY = (uint)Math.Floor(startPoint.Y);
uint height = (uint)Math.Floor(corpSize.Height);
uint width = (uint)Math.Floor(corpSize.Width);
// Refine the start point and the size.
if (startPointX + width > decoder.PixelWidth)
{
startPointX = decoder.PixelWidth - width;
}
if (startPointY + height > decoder.PixelHeight)
{
startPointY = decoder.PixelHeight - height;
}
// Create cropping BitmapTransform to define the bounds.
BitmapTransform transform = new BitmapTransform();
BitmapBounds bounds = new BitmapBounds();
bounds.X = startPointX;
bounds.Y = startPointY;
bounds.Height = height;
bounds.Width = width;
transform.Bounds = bounds;
// Get the cropped pixels within the the bounds of transform.
PixelDataProvider pix = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.ColorManageToSRgb);
byte[] pixels = pix.DetachPixelData();
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
var file = await storageFolder.CreateFileAsync("test.jpeg", CreationCollisionOption.ReplaceExisting);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
// Set the pixel data to the cropped image.
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
width,
height,
decoder.DpiX,
decoder.DpiY,
pixels);
// Flush the data to file.
await encoder.FlushAsync();
}
The helper methods i use are....
private async Task<string> ToBase64(byte[] image, uint height, uint width, double dpiX = 96, double dpiY = 96)
{
var encoded = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, height, width, dpiX, dpiY, image);
await encoder.FlushAsync();
encoded.Seek(0);
var bytes = new byte[encoded.Size];
await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes);
}
private byte[] ImageToByteArray(WriteableBitmap wbm)
{
using (Stream stream = wbm.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
The code that picks an image and converts to writable bitmap is
WriteableBitmap image;
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var bitmp = new BitmapImage();
// Application now has read/write access to the picked file
var filePath = await file.OpenReadAsync();
bitmp.SetSource(filePath);
proPic.Source = bitmp;
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
image = new WriteableBitmap(1, 1);
image.SetSource(stream);
}
imageT = await ToBase64(ImageToByteArray(image), 100, 100, 96, 96);
pic = 1;
}
else
{
//OutputTextBlock.Text = "Operation cancelled.";
}
When i compare the base64string i get from the helper methods with http://www.dailycoding.com/utils/converter/imagetobase64.aspx
The both are not the same.
changing the file into в base64
public async Task<string> GetBase64(string name)
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync(name);
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(file.Path));
byte[] fileBytes = null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return Convert.ToBase64String(fileBytes);
}
I want to share the screenshot of the app on Twitter, Facebook, etc. This is my code: it saves the picture, but doesn't open the share media task. I know the problem is in the path :{
var wb = new WriteableBitmap(LayoutRoot, new TranslateTransform());
using (var mediaLibrary = new MediaLibrary()) {
using (var stream = new MemoryStream()) {
var fileName = string.Format("{0}.jpg", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"));
wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
mediaLibrary.SavePicture(fileName, stream);
shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = fileName;
shareMediaTask.Show();
}
}
How can I get the saved picture's path?
Isn't it possible to just simply take a screenshot and share it without saving it on the phone?
To get the real path for the MediaLibrary file, you'll need to use the GetPath() extension method, something like;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
...
var picture = mediaLibrary.SavePicture(fileName, stream);
shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = picture.GetPath();
shareMediaTask.Show();
For sharing the screen shot it is not required to save the image , in windows 8.1 it is very easy.
Here is the code, enjoy!
async void dataTransferMgr_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
DataRequest request = args.Request;
request.Data.Properties.Title = "Title";
request.Data.Properties.Description = "brief description";
request.Data.SetText("detailed information");
RandomAccessStreamReference imageStreamRef = await ScreenshotToStreamReferenceAsync(yourChartControlName);
request.Data.Properties.Thumbnail = imageStreamRef;
request.Data.SetBitmap(imageStreamRef);
}
private async Task ScreenshotToStreamAsync(FrameworkElement element, IRandomAccessStream stream)
{
var renderTargetBitmap = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var dpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
dpi,
dpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
private async Task<RandomAccessStreamReference> ScreenshotToStreamReferenceAsync(FrameworkElement element)
{
var ms = new InMemoryRandomAccessStream();
await ScreenshotToStreamAsync(element, ms);
ms.Seek(0);
return RandomAccessStreamReference.CreateFromStream(ms);
}
I have a WriteableBitmap that I need to save in a file. I have a feeling I need the AsStream() extension method on WriteableBitmap.PixelBuffer. However, I don't see that extension method on my WriteableBitmap.
Should AsStream() be on all WriteableBitmaps?
Once I get AsStream(), what do I do next?
Here you go !!!
using System.Runtime.InteropServices.WindowsRuntime;
private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
{
string FileName = "MyFile.";
Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
switch (fileFormat)
{
case FileFormat.Jpeg:
FileName += "jpeg";
BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
break;
case FileFormat.Png:
FileName += "png";
BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
break;
case FileFormat.Bmp:
FileName += "bmp";
BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
break;
case FileFormat.Tiff:
FileName += "tiff";
BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
break;
case FileFormat.Gif:
FileName += "gif";
BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
break;
}
var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
Stream pixelStream = WB.PixelBuffer.AsStream();
byte[] pixels = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
(uint)WB.PixelWidth,
(uint)WB.PixelHeight,
96.0,
96.0,
pixels);
await encoder.FlushAsync();
}
return file;
}
private enum FileFormat
{
Jpeg,
Png,
Bmp,
Tiff,
Gif
}