Load an image from media library onto canvas with WriteableBitmap image? - c#

I am trying to load a picture selected from media library of windows phone and I have done upto choosing the required picture and I am unable to load image onto my canvas named area with this code :
void photochoosertask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
WriteableBitmap bitMap = new WriteableBitmap(200,200);
Extensions.LoadJpeg(bitMap, e.ChosenPhoto);
Canvas.SetLeft(area, 10);
Canvas.SetTop(area, 10);
bitMap.Render(area, null);
bitMap.Invalidate();
}
}
But I am unable to do with this code..any suggestions..??
or how to do this task ? Is this the correct way ?
Thanks

if (e.TaskResult == TaskResult.OK)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap b = new WriteableBitmap(bi);
Image img = new Image();
img.Source = b;
Canvas.SetLeft(img, 10);
Canvas.SetTop(img, 10);
area.Children.Add(img);
}

In order to show the bitmap in your Canvas you would have to add an Image control to its Children collection, which uses the bitmap as its Source:
var bitmap = new WriteableBitmap(200, 200);
Extensions.LoadJpeg(bitmap, e.ChosenPhoto);
var image = new Image();
image.Source = bitmap;
Canvas.SetLeft(image, 10);
Canvas.SetTop(image, 10);
area.Children.Add(image);
As e.ChosenPhoto is a stream, you may perhaps also use a BitmapImage instead of a WriteableBitmap, and set its source stream to e.ChosenPhoto. You may then set the size of the Image control to the desired values.
var bitmap = new BitmapImage();
bitmap.SetSource(e.ChosePhoto);
var image = new Image();
image.Source = bitmap;
image.Width = 200;
image.Height = 200;
Canvas.SetLeft(image, 10);
Canvas.SetTop(image, 10);
area.Children.Add(image);

Related

Printed wpf visual is clipped in landscape mode under Windows 8.1

I have a simple wpf desktop application which prints a bitmap in landscape mode.
Under Windows 8/8.1 the printout is clipped on the bottom of the page while under Windows 7 it is printed correctly.
The code is really simple: load a bitmap, put it into an Image object, measure the printable area, arrange the image and print.
void printButton_Click(object sender, RoutedEventArgs e)
{
var pd = new PrintDialog();
if (!pd.ShowDialog().Value)
{
return;
}
pd.PrintTicket.PageOrientation = PageOrientation.Landscape;
pd.PrintTicket.PageBorderless = PageBorderless.None;
var printingCapabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri("D:\\printTest.bmp");
bitmapImage.EndInit();
var imageuiElement = new Image { Source = bitmapImage };
var desiredSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
imageuiElement.Measure(desiredSize);
imageuiElement.Arrange(new Rect(new Point(printingCapabilities.PageImageableArea.OriginWidth, printingCapabilities.PageImageableArea.OriginHeight), imageuiElement.DesiredSize));
pd.PrintVisual(imageuiElement, "MyImage");
}
The bitmap size is 1518 x 1092 pixels, 96 DPI, which is 40.2 x 28.9 cm.
I have found the question Cannot print a document with landscape orientation under Windows 8 (WPF, .NET 4.0)
but there is no good response for my issue (additionally I have no problem with printing as landscape itself).
I have tested it with different printers of different vendors, the printouts are clipped in all of them. A software CutePDF writer prints it to PDF correctly.
Any help appreciated.
It seems that Windows 8 does not draw ui elements outside of their container bounds. This is why the printout was clipped at the bottom.
Anyway, I ended up with a code like this, which is able to print a centered bitmap on a landscape page:
printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDialog.PrintTicket.PageBorderless = PageBorderless.None;
var printingCapabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
if (printingCapabilities.PageImageableArea == null)
{
return;
}
var document = new FixedDocument();
document.DocumentPaginator.PageSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
foreach (var imageStream in imageStreams)
{
document.Pages.Add(GeneratePageContent(imageStream, printingCapabilities, printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));
}
try
{
printDialog.PrintDocument(document.DocumentPaginator, GlobalConstants.SoftwareName);
}
private PageContent GeneratePageContent(Stream imageStream, PrintCapabilities printingCapabilities, double paperWidth, double paperHeight)
{
imageStream.Seek(0, SeekOrigin.Begin);
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = imageStream;
bmp.EndInit();
var margin = new Thickness();
var pageSize = new Size();
if (printingCapabilities.PageImageableArea != null)
{
margin = new Thickness(
printingCapabilities.PageImageableArea.OriginWidth,
printingCapabilities.PageImageableArea.OriginHeight,
printingCapabilities.PageImageableArea.OriginWidth,
printingCapabilities.PageImageableArea.OriginHeight);
pageSize = new Size(printingCapabilities.PageImageableArea.ExtentWidth, printingCapabilities.PageImageableArea.ExtentHeight);
}
var imageUiElement = new Image
{
Source = bmp,
Margin = margin
};
var canvas = new Grid { Width = paperWidth, Height = paperHeight };
canvas.Children.Add(imageUiElement);
var fixedPage = new FixedPage
{
Width = paperWidth,
Height = paperHeight
};
fixedPage.Children.Add(canvas);
var pageContent = new PageContent();
((IAddChild)pageContent).AddChild(fixedPage);
pageContent.Measure(pageSize);
pageContent.Arrange(new Rect(new Point(), pageSize));
pageContent.UpdateLayout();
return pageContent;
}

Capture the screen selected by Current Form in WPF?

I am creating a application which can capture the screen which is selected by current active windows form and make user aware by setting it as the background of it. Please refer the image
But my problem is i cant get the size of the active window size. This is the code i have been working on
private void button5_Click(object sender, RoutedEventArgs e)
{
Image b = null;
int w = (int)this.Width;
int h = (int)this.Height;
**System.Drawing.Size sz = this.Size;
System.Drawing.Point loc = this.Location;**
Hide();
System.Threading.Thread.Sleep(500);
using (b = new Bitmap(w, h))
{
using (Graphics g = Graphics.FromImage(b))
{
g.CopyFromScreen(loc, new System.Drawing.Point(0, 0), sz);
}
Image x = new Bitmap(b);
ImageBrush myBrush = new ImageBrush();
x.Save(#"C:\Users\DZN\Desktop\testBMP.jpeg", ImageFormat.Jpeg);
myBrush.ImageSource = new BitmapImage(new Uri(#"C:\Users\DZN\Desktop\testBMP.jpeg", UriKind.Absolute));
this.Background = myBrush;
}
Show();
}
In the bolded lines i get the error saying WpfApplication1.MainWindow' does not contain a definition for 'Size, location. but this works well in windows forms. Any help is hugly appreciated. Thank you.
WPF Window doesn't have a size property instead you can use ActualWidth and ActualHeight. Same way it doesn't exposes Location also but you can use Left and Top properties.
All the above properties are of type double so you need a cast to appropriate type.
System.Drawing.Size sz = new System.Drawing.Size((int)ActualWidth, (int)ActualHeight);
System.Drawing.Point loc = new System.Drawing.Point((int)Left, (int)Top);

Select an image from rectangle using writeablebitmap

I have written an application in silverlight, I am placing a rectangle on the image and want to select the part of image covered by rectangle and show it on a image control on click of a button.
I am not good at handling ratios and image manipulation things, so I am unable to get it right way.
The code for the same goes as below, and would appreciate, if anyone could suggest me a way or solution to get around with this.
public void CaptureImage(object sender, RoutedEventArgs e)
{
BitmapImage bitmapImage = new BitmapImage();
//// bitmapImage.CreateOptions = BitmapCreateOptions.None;
bitmapImage = NewImage;
////calculate bounding box
int originalWidth = bitmapImage.PixelWidth;
int originalHeight = bitmapImage.PixelHeight;
int newSmallWidth = (int)SquareBlue.Width;
int newSmallHeight = (int)SquareBlue.Height;
////generate temporary control to render image
Image temporaryImage = new Image { Source = bitmapImage, Width = newSmallWidth, Height = newSmallHeight };
////create writeablebitmap
WriteableBitmap wb = new WriteableBitmap(newSmallWidth, newSmallHeight);
TranslateTransform t = new TranslateTransform();
t.X = -5;
t.Y = -5;
wb.Render(temporaryImage, t);
wb.Invalidate();
myImage.Source = wb;
}
Whenever this code gets executed, whole image gets snapped, instead of the part selected by rectangle. Could anyone, guide me as what I am doing wrong here.
I'd recommend that you use the Crop method the WriteableBitmapEx library provides.

set height of icon Image template programatically

I have one column in my datagrid which contains Icons.
for this I have one celltemplate added to column programatically.
var imageFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Image));
imageFactory.SetBinding(System.Windows.Controls.Image.SourceProperty, imageBinding);
imageFactory.SetValue(System.Windows.Controls.Image.StretchProperty, Stretch.None);
if (config.Font != null)
{
double height = config.Font.Size;
imageFactory.SetValue(FrameworkElement.HeightProperty, height);
}
var dataTemplate = new DataTemplate { VisualTree = imageFactory };
statusColumn.CellTemplate = dataTemplate;
view.DataGrid.Columns.Add(statusColumn);
when I set Height property externally it crops the image instead of resizing image to 'height' value.
how to set image height to specific value.
please suggest.
try this
double size = 14.0;
BitmapImage bmp = new BitmapImage(new Uri("MyIcon.ico", UriKind.RelativeOrAbsolute));
FrameworkElementFactory icon = new FrameworkElementFactory(typeof(Image));
icon.SetValue(Image.SourceProperty, bmp);
icon.SetValue(Image.WidthProperty, size);
icon.SetValue(Image.HeightProperty, size);
UPDATE try this
Style sBase = (Style)this.Resources["BaseButtonStyle"];
Style sNew = new Style(typeof(Image), sBase);
sNew.Setters.Add(new Setter(HeightProperty, 20d));
REFERENCE
See this
I used BitmapImage.DecodePixelHeight and it solved my problem. :)
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.DecodePixelHeight = font.Size <= 9 ? font.Size + 2 : font.Size;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();

Can I use Bitmap in a Brush, in Visual C#?

I want to use a picture instead of color in this code:
brush = new SolidBrush(Color.Red);
Ex: brush = new SolidBrush(PICTURE);
What should I do?
Maybe you can use one of the Fill methods in Graphics class and a TextureBrush?
Image image = Image.FromFile("bitmap file path");
TextureBrush textureBrush = new TextureBrush(image);
graphics.FillEllipse(myTextureBrush, 0, 0, 200, 200);
You could use the TextureBrush to do so
private void Button2_Click(System.Object sender, System.EventArgs e)
{
try
{
Bitmap image1 = (Bitmap) Image.FromFile(#"C:\Documents and Settings\" +
#"All Users\Documents\My Music\music.bmp", true);
TextureBrush texture = new TextureBrush(image1);
texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
Graphics formGraphics = this.CreateGraphics();
formGraphics.FillEllipse(texture,
new RectangleF(90.0F, 110.0F, 100, 100));
formGraphics.Dispose();
}
catch(System.IO.FileNotFoundException)
{
MessageBox.Show("There was an error opening the bitmap." +
"Please check the path.");
}
}
Code snippet taken from MSDN.
Use ImageBrush.

Categories