UWP drag and drop from WebView onto Canvas - c#

I tried this code. I drag Image from WebView to Canvas. But nothing to be show. Maybe dropped data is URL or html data. BUt I don't know how to convert html data to Bitmap data.
private async void drop(object sender, DragEventArgs e)
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
Point drop = e.GetPosition(Board);
var storageFile = items[0] as StorageFile;
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(await storageFile.OpenAsync(FileAccessMode.Read));
Image img = new Image();
img.Source = bitmapImage;
img.Width = 200;
img.Height = 150;
Canvas.SetLeft(img, drop.X);
Canvas.SetTop(img, drop.Y);
Board.Children.Add(img);
}
}
}
XAML is below.
<WebView x:Name="WebView" Source="https://google.com" ScriptNotify="Notify" NavigationCompleted="Completed" ></WebView>
<Canvas AllowDrop="True" DragOver="dragOver" Drop="drop"></Canvas>

Related

Attach Image/ImageBrush from code behind

I'm trying to add an Image as the background of a UserControl. Depending on the value of a variable I need to change that background but whatever the path or Uri format I use, the background does not change.
I've seen lots of questions here in stackoverflow but none fixes my single problem.
I let the code below:
if (callback.liveUvis.ContainsUVI(uvi))
{
this.Status.Text = "LIVE";
ImageBrush imgB = new ImageBrush();
BitmapImage btpImg = new BitmapImage();
btpImg.UriSource = new Uri(#"///IMG///Live///bck_frame_info_video_live.png", UriKind.Relative);
//imgB.ImageSource = new BitmapImage(new Uri("~/IMG/Live/bck_frame_info_video_live.png", UriKind.RelativeOrAbsolute));
//imgB.ImageSource = new BitmapImage(new Uri("ms-appx:///IMG/Live/bck_frame_info_video_live.png"));
imgB.ImageSource = btpImg;
this.Background = imgB;
}
I'm facing the same problem when trying to attach an image... I guess it's up to the Uri format also, but I let the code too just in case :)
private void setIcon_Desc(string dd)
{
try
{
Image img = new Image();
img.Source = new BitmapImage(new Uri(this.BaseUri, "IMG/pictos_small/white/160dpi/" + dd + ".png"));
img.Stretch = Stretch.None;
this.Icon = img;
this.Sport.Text = callback.disc.getDescription(dd).ToUpper();
}
catch(Exception ex)
{
callback.exception.writeExceptions(ex);
}
}
Thanks in advance!
I can reproduce your issue when changing the background of a user control.
The current workaround I used was changing the background of root UIElement in the control.
<Grid x:Name="container">
<Grid.Background>
<ImageBrush Stretch="Fill" ImageSource="Images/bg-blue.png"/>
</Grid.Background>
<StackPanel>
<TextBlock>Hello World</TextBlock>
<Button Click="Button_Click">Change Background</Button>
<Image x:Name="display"></Image>
</StackPanel>
</Grid>
public sealed partial class MyUserControl : UserControl
{
public MyUserControl()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ImageBrush imgB = new ImageBrush();
BitmapImage btpImg = new BitmapImage();
btpImg.UriSource = new Uri(#"ms-appx:///images/bg-light-blue.png");
imgB.ImageSource = btpImg;
container.Background = imgB;
}
}

display an image from file in wpf isn't working?

I have a button b3 and an image named pictureBox1 . Im using WPF, however I'm using the winforms openFileDialog instead of the one that comes with WPF :
below is the code that I put inside the click event of my button :
private void b3_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
Image i = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
i.Source = src;
i.Stretch = Stretch.Uniform;
//int q = src.PixelHeight; // Image loads here
}
}
When I click the button and select an icon. The icon doesn't appear in the pictureBox1.
Can someone please explain why the code above doesn't show the icon inside the pictureBox?
You need to assign your image to the pictureBox, else you wont see it on your screen and you only made the image object in memory.
private void b3_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialogIcon = new System.Windows.Forms.OpenFileDialog();
if (openDialogIcon.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(openDialogIcon.FileName, UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
pictureBox1.Source = src;
}
}
Try to drag and drop a Image control in your window
...
//imageStretch <- the name of Image control
i.Stretch = Stretch.Uniform;
//int q = src.PixelHeight; // Image loads here
imageStretch.Source = src;
...

How do I get an image to save after rotation at runtime?

I am working with WPF and I have an application that the user loads an image file into a RichTextBox and they can rotate the image and print it. I am not sure as to why the image after it has been rotated will not print as it is displayed on the screen. Instead it prints the original. I am new to this so any help would be greatly appreciated!
The following is the code for my application. Code when the retrieve file Button is clicked:
private void retrieve_button_Click(object sender, RoutedEventArgs e)
{
//Retrieve the file or image you are looking for
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Formats|*.jpg;*.png;*.bmp;*.gif;*.ico;*.txt|JPG Image|*.jpg|BMP image|*.bmp|PNG image|*.png|GIF Image|*.gif|Icon|*.ico|Text File|*.txt";
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
try
{
System.Windows.Controls.RichTextBox myRTB = new System.Windows.Controls.RichTextBox();
{
Run myRun = new Run();
System.Windows.Controls.Image MyImage = new System.Windows.Controls.Image();
MyImage.Source = new BitmapImage(new Uri(of.FileName, UriKind.RelativeOrAbsolute));
InlineUIContainer MyUI = new InlineUIContainer();
MyUI.Child = MyImage;
rotateright_button.IsEnabled = true;
print_button.IsEnabled = true;
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(myRun);
paragraph.Inlines.Add(MyUI);
FlowDocument document = new FlowDocument(paragraph);
richTextBox.Document = document;
}
}
catch (ArgumentException)
{
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
}
When the rotate right button is clicked the following code is executed:
RotateTransform cwRotateTransform;
private void rotateright_button_Click(object sender, RoutedEventArgs e)
{
richTextBox.LayoutTransform = cwRotateTransform;
if (cwRotateTransform == null)
{
cwRotateTransform = new RotateTransform();
}
if (cwRotateTransform.Angle == 360)
{
cwRotateTransform.Angle = 0;
}
else
{
cwRotateTransform.Angle += 90;
}
}
After the Image has been loaded and rotated the user can use the following code to print:
private void InvokePrint(object sender, RoutedEventArgs e)
{
System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
if ((bool)printDialog.ShowDialog().GetValueOrDefault())
{
FlowDocument flowDocument = new FlowDocument();
flowDocument = richTextBox.Document;
flowDocument.ColumnWidth = printDialog.PrintableAreaWidth;
flowDocument.PagePadding = new Thickness(65);
IDocumentPaginatorSource iDocPag = flowDocument;
printDialog.PrintDocument(iDocPag.DocumentPaginator, "Print Document");
}
}
Try this (substitute yourImageControl in the first line, specify which RotateFlipType you want and be sure to reference the System.Drawing dll):
System.Drawing.Bitmap bitmap = BitmapSourceToBitmap((BitmapSource)YourImageControl.Source);
bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource bitmapsource)
{
System.Drawing.Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
return bitmap;
}
Another option for conversion...
P.S. You would get a better answer in less time if you posted some code and told us more about what you have tried.

how to display image in a grid using C# for WP8?

i need to insert an image in a WP8. i have a stack of images. once i click the image, it has to be set as background for a grid. so i created an empty "grid1" and button. wrote the below code in the button click event, but the image doesnot get displayed !
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
It is hard to know if your image file is in the correct place and set to the right build type. I'd suggest adding an event handler to the Image failed event.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, e) => MessageBox.Show("Failed to load: " + e.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(
new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
myBrush.ImageSource = image.Source;
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
First, you don't need to use Image to fill the background from URI.
private void bg6_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"));
// Grid grid1 = new Grid();
grid1.Background = myBrush;
}
Second, it is a WAY better to design it in XAML and manipulate it visibility and source from code by creating the helper class with visibility and source property. Don't forget to implement INotifyPropertyChanged interface into that class.
<Grid x:Name="myGrid" DataContext="{Binding}" Visibility="{Binding Path=VisibleProperty}">
<Grid.Background>
<ImageBrush x:Name="myBrush" ImageSource="{Binding Path=SourceProperty}"></ImageBrush>
</Grid.Background>
And in code:
private void bg6_Click(object sender, RoutedEventArgs e)
{
myGrid.DataContext=new myImagePresenterClass(new Uri("\\PhoneApp2\\PhoneApp2\\Assets\\bg\\bg5.jpg"), Visibility.Visible)
}
public class myImagePresenterClass:INotifyPropertyChanged
{
private URI sourceProperty
Public URI SourceProperty
{
get
{
return sourceProperty;
}
set
{
sourceProperty=value;
if(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs("SourceProperty"));}
}
}
//Don't forget to implement the Visible property the same way as SourceProperty and the class constructor.
}
i found the mistake... i'm sorry guys. i didn't follow the syntax correctly. i missed the '#' in the Uri method. the correct way to represent this is
private void bg1_Click(object sender, RoutedEventArgs e)
{
System.Windows.Media.ImageBrush myBrush = new System.Windows.Media.ImageBrush();
Image image = new Image();
image.ImageFailed += (s, i) => MessageBox.Show("Failed to load: " + i.ErrorException.Message);
image.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(#"/Assets/bg/bg1.jpg/", UriKind.RelativeOrAbsolute));
myBrush.ImageSource = image.Source;
grid1.Background = myBrush;
}

How to Update/replace image in WPF by clicking button

So I have an image that when the user clicks on a button it will change it to a new item. However, whenever the user clicks on one of the button, the window will go blank. How can I get this to work? Thank you.
private void Next_Click(object sender, RoutedEventArgs e)
{
if (imageNumber > 6)
{
imageNumber = 1;
}
imageNumber++;
string sUri = string.Format("#/Resources/{0}", imageSource[imageNumber]);
Uri src = new Uri(sUri, UriKind.Relative);
var bmp = new BitmapImage(src);
img.Source = bmp;
}
xaml
<Image x:Name="img">
<Image.Source>
<BitmapImage UriSource="Resources/BlackJackTut-1.jpg" />
</Image.Source>
</Image>
In WPF application you can do same also with "pack://application:,,,/resources/imagename.png".
This way called Pack URI. This is static, but with these code you can do same an even use resource ;)
Put image in Resources.
private BitmapImage ConvertBitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(memoryStream.ToArray());
bitmapImage.EndInit();
return bitmapImage;
}
and then use this:
private void btn_Click(object sender, RoutedEventArgs e)
{
this.Img.Source = ConvertBitmapToBitmapImage(Properties.Resources.iamge1);
}
Just make an Image outside the mainWindow.
Then:
myImageOnScreen.Source = myImageOffScreen.Source;

Categories