UWP - ImageBrush full path to ImageSource - win-universal-app

I have an ellipse and I want to fill it with image. And I would like to set full path to the image to ImageSource property of ImageBrush. But I wasn't able to accomplish it.
I've tried to add:
C:/Users/someuser/Pictures/untitled.png
C:\\Users\\someuser\\Pictures\\untitled.png which came from FilePicker
C:\Users\misko\Pictures\untitled.png.
But non of this works. Can you please explain to me how to properly set full path?

You have to open the file first using FilePicker
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
grid.Background = new ImageBrush
{
ImageSource = bitmapImage
};
}

Related

NodeJS: Updating Exif data and saving image using PIEXIF

I need to update orientation tag(EXIF data) for the uploaded image. I am using "PIEXIF" for this. I am not using express but swagger. The code I've written is:
//Get the uploaded buffer
var _originalBuffer = req.swagger.params.uploadedFile.value.buffer;
let Duplex = require('stream').Duplex;
//Create stream from buffer. This stream is required later to send to cloud.
let _uploadedFileStream = new Duplex();
_uploadedFileStream.push(_originalBuffer);
_uploadedFileStream.push(null);
//Create base 64 string so that "PIEXIF" can read exif data from it.
const jpegData = "data:image/jpeg;base64, " + createStringFromBuffer(_originalBuffer, 'base64');
//Read exif data.
var _exifData = piexif.load(jpegData);
//Create a copy of exif data. Will be used to create a new image with updated orientation tag.
var _exifDataCopied = {};
for (var key in _exifData) {
_exifDataCopied[key] = _exifData[key];
}
//Update orientation tag.
if (_exifDataCopied["0th"][piexif.ImageIFD.Orientation])
_exifDataCopied["0th"][piexif.ImageIFD.Orientation] = 1;
//Example taken from https://www.npmjs.com/package/piexifjs
//From here onwards, there seems to be an issue.
var exifbytes = piexif.dump(_exifDataCopied);
var newData = piexif.insert(exifbytes, createStringFromBuffer(_originalBuffer, 'binary'));
var newJpeg = new Buffer(newData);
//Create a new stream and save it as image back.
let _updatedFileStream = new Duplex();
_updatedFileStream.push(newJpeg);
_updatedFileStream.push(null);
var fs = require('fs');
var writeStream = fs.createWriteStream("./uploads/" + "Whatever.jpg")
The issue is there is no error thrown by the code. The image is also getting saved in the directory but it is corrupted. I can not preview it. Since, the code does not breaks anywhere, I am confused what could be the issue? The function to convert buffer to string with different encoding(since I need it a lot) is:
var createStringFromBuffer = function(_buffer, _encoding) {
return Buffer.from(_buffer).toString(_encoding);
}
Can someone point out where I am mistaking? I am using the example given Here

Sharing image via my app in xamarin.forms

I want to share an image. Sharing options should contain my app xyz. For example if I open an image and want to share it on instagram sharing options contains instagram,facebook,twitter,email etc. Like that my app should be in sharing options. How can I do that in xamarin.forms(both ios and android).
I think the app icon is created in a directory that is private to your app, so other apps wont be able to get at it.
You will need to save it out somewhere where the other apps can access it then share it from that location some thing like this:
public void Share (string title, string content)
{
if (string.IsNullOrEmpty (title) || string.IsNullOrEmpty (content))
return;
Bitmap b = BitmapFactory.DecodeResource(Resources,Resource.Drawable.icon_120);
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose ();
var imageUri = Android.Net.Uri.Parse ($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent ();
sharingIntent.SetAction (Intent.ActionSend);
sharingIntent.SetType ("image/*");
sharingIntent.PutExtra (Intent.ExtraText, content);
sharingIntent.PutExtra (Intent.ExtraStream, imageUri);
sharingIntent.AddFlags (ActivityFlags.GrantReadUriPermission);
StartActivity (Intent.CreateChooser (sharingIntent, title));
}
Also add ReadExternalStorage and WriteExternalStorage permissions to your app.
Let me know if that works.

Microsoft bot framework : How to define the image path which exists in the solution itself

I have stored the image inside the project itself, now I would like to display the image on the hero card, so I have mentioned the relative path. However the image is not appearing....
List<CardImage> cardImages = new List<CardImage>();
cardImages.Add(new CardImage(url: "~/duck-on-a-rock.jpg", alt:"image1"));
But when I referred the image from some website and mention the same path on the page like below that time the image is appearing.
List<CardImage> cardImages = new List<CardImage>();
cardImages.Add(new CardImage(url: "http://www.publicdomainpictures.net/pictures/30000/t2/duck-on-a-rock.jpg", alt:"image1"));
Is it not possible to keep the image inside the project folder?
This is a super old question, but google me brought here nonetheless. The solution I came across was to create a data url for your local resource. In node.js:
const imageData = fs.readFileSync(path.join(__dirname, '../resources/logo.png'));
const base64Image = Buffer.from(imageData).toString('base64');
const inlinePng = {
name: 'logo.png',
contentType: 'image/png',
contentUrl: `data:image/png;base64,${ base64Image }`
};
With an svg, you can skip the base64 encode:
const svgData = fs.readFileSync(path.join(__dirname, './resources/logo.svg'));
const inlineSvg = {
name: 'logo',
contentType: 'image/svg',
contentUrl: `data:image/svg+xml;utf8,${ svgData }`,
};
See Microsoft's docs for reference and C# samples.
Using DI approach: Pass one extra IHostingEnvironment variable to your dialog constructor.
public DialogBot(ConversationState conversationState, T dialog, ConcurrentDictionary<string, ConversationReference> conversationReferences, IHostingEnvironment env)
{
_conversationReferences = conversationReferences;
_conversationState = conversationState;
_dialog = dialog;
_env = env;
}
And later you can use _env.WebRootPath to access your local storage (for bot emulator) or use environmental variable WEBSITE_HOSTNAME if you run bot in azure.
private async Task SendWelcomeCardAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
var card = new HeroCard();
card.Title = "Welcome to Bot Framework!";
var host = new Uri(Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME") != null ? ("https://" + Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")) : _env.WebRootPath + "/");
var img = new Uri(host, "MyImage.jpg");
card.Images = new List<CardImage>() { new CardImage(img.AbsoluteUri) };
var response = MessageFactory.Attachment(card.ToAttachment());
await turnContext.SendActivityAsync(response, cancellationToken);
}
I simply dropped MyImage.jpg image to wwwroot project folder and marked it as Content

converting Image raw data to bitmapimage in windows universal app

I am trying to implement a windows universal application. I am facing one issue for converting the image raw data(byte array) to the BitmapImage control. I don't know the type of the image raw data. I used the below code,
private async Task<BitmapImage> ByteArrayToBitmapImage(byte[] byteArray)
{
var bitmapImage = new BitmapImage();
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(byteArray.AsBuffer());
stream.Seek(0);
bitmapImage.SetSource(stream);
return bitmapImage;
}
Image is not displayed in window. When I debugging , found that height & width of bitmapImage object is 0.
if anybody know the solution for this, please help me
Finally my issue solved , when I used the below code,
var bmp = new WriteableBitmap(320, 240);
using (var stream = bmp.PixelBuffer.AsStream())
{
stream.Write(bytes, 0, bytes.Length);
myImage.Source = bmp;
}
I'm using the same code and in works for me but I create BitmapImage and set its source on dispatcher's thread - maybe that's the key to your problem.

How to create WriteableBitmap from BitmapImage?

I could create WriteableBitmap from pictures in Assets.
Uri imageUri1 = new Uri("ms-appx:///Assets/sample1.jpg");
WriteableBitmap writeableBmp = await new WriteableBitmap(1, 1).FromContent(imageUri1);
but, I can't create WriteableBitmap from Pictures Directory,(I'm using WinRT XAML Toolkit)
//open image
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StorageFile file = await picturesFolder.GetFileAsync("sample2.jpg");
var stream = await file.OpenReadAsync();
//create bitmap
BitmapImage bitmap2 = new BitmapImage();
bitmap2.SetSource();
bitmap2.SetSource(stream);
//create WriteableBitmap, but cannot
WriteableBitmap writeableBmp3 =
await WriteableBitmapFromBitmapImageExtension.FromBitmapImage(bitmap2);
Is this correct ?
This is a total contrivance, but it does seem to work ...
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var folder = KnownFolders.PicturesLibrary;
var file = await folder.GetFileAsync("test.jpg");
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
Here's the way reading an image to a WriteableBitmap works as Filip noted:
StorageFile imageFile = ...
WriteableBitmap writeableBitmap = null;
using (IRandomAccessStream imageStream = await imageFile.OpenReadAsync())
{
BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(
imageStream);
BitmapTransform dummyTransform = new BitmapTransform();
PixelDataProvider pixelDataProvider =
await bitmapDecoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied, dummyTransform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.ColorManageToSRgb);
byte[] pixelData = pixelDataProvider.DetachPixelData();
writeableBitmap = new WriteableBitmap(
(int)bitmapDecoder.OrientedPixelWidth,
(int)bitmapDecoder.OrientedPixelHeight);
using (Stream pixelStream = writeableBitmap.PixelBuffer.AsStream())
{
await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
}
}
Note that I am using the pixel format and alpha mode Writeable Bitmap uses and that I pass .
WriteableBitmapFromBitmapImageExtension.FromBitmapImage() works by using the original Uri used to load BitmapImage and IIRC it only works with BitmapImages from the appx. In your case there isn't even a Uri since loading from Pictures folder can only be done by loading from stream, so your options from the fastest to slowest (I think) are:
Open the image as WriteableBitmap from the get go, so that you don't need to reopen it or copy bits around.
If you need to have two copies - open it as WriteableBitmap and then create a new WriteableBitmap of same size and copy the pixel buffer.
If you need to have two copies - track the path used to open the first bitmap and then create a new WriteableBitmap by loading it from the same file as the original one.
I think option 2 might be faster than option 3 since you avoid decoding a compressed image twice.

Resources