silverlight draw on bitmap - c#

Image img = new Bitmap(Image.FromFile(file.FullName));
using (Graphics g = Graphics.FromImage(img)){
g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}
like this
how to do in sliverlight?

Use WriteableBitmap class.
References:
Rendering XAML to a JPEG using Silverlight 3
Silverlight 3.0: WriteableBitmap
Silverlight 3's New Writeable Bitmap
Example:
With WritableBitmap, you can just draw something on a Control or Canvas and then save it to a bitmap using it's public WriteableBitmap(UIElement element,Transform transform) constructor.

You don't need to render a SL Rectangle into the WriteableBitmap. The WriteableBitmapEx open source library is perfect for this. See the project site for an example of the DrawRectangle method.
http://writeablebitmapex.codeplex.com
There are also live samples, including the Shape sample.
You can also find the code of the samples in the source code repository.

You can use a WriteableBitmap for this. Create a Canvas and draw your elements on the Canvas, load other images etc. Then once you are done rendering on the Canvase you can create the WriteableBitmap from the Canvas and then do what every you need.
In the example below I assigned the bitmap as the Source of an Image element to show that the final result.
Canvas canvas = new Canvas();
UIElement ellipse = new Ellipse()
{ Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.Red) };
Canvas.SetLeft(ellipse, 100);
Canvas.SetTop(ellipse, 100);
canvas.Children.Add(ellipse);
WriteableBitmap bmp = new WriteableBitmap(canvas, null);
myImage.Source = bmp;

Related

CSharp Windows Form Picturebox Draw Small Image Without Quality Loss

I'm trying to create a level editor using Windows Forms for my monogame project and need to draw small pixel based images to a picture box with no quality loss when scaled. In monogame when I need to do this I can just set the draw type to PointClamp and then each pixel is drawn as is instead of being pixelated when zoomed; I was hoping for something like this via a picturebox. Right now it looks like this But I'd prefer a more crisp and clean image like this (The second is how it'll appear in monogame). I haven't uploaded any code for this, but just assume I grabbed an image from the filestream and used the bitmap constructor to scale it up (don't think that's relevent but I'll just put it out there).
Image croppedImage, image = tileMap.tileBox.Image;
var brush = new SolidBrush(Color.Black);
try { croppedImage = CropImage(image, tileMap.highlightedRect); } catch {
return; // If crop target is outside bounds of image then return
}
float scale = Math.Min(higlightedTileBox.Width / croppedImage.Width, higlightedTileBox.Height / image.Height);
var scaleWidth = (int)(higlightedTileBox.Width * scale);
var scaleHeight = (int)(higlightedTileBox.Height * scale);
try { higlightedTileBox.Image = new Bitmap(croppedImage, new Size(scaleWidth, scaleHeight)); } catch {
return; // Image couldn't be scaled or highlighted tileBox couldn't be set to desired image
}
CropImage:
private static Image CropImage(Bitmap img, Rectangle cropArea) {
return img.Clone(cropArea, img.PixelFormat);
}
private static Image CropImage(Image img, Rectangle cropArea) {
return CropImage(new Bitmap(img), cropArea);
}
The code above is my current method in it's entirety. tileMap is a form and tilebox is the picturebox within that form.image is the full spritesheet texture before being cropped to what the user has highlighted. After being cropped I attempt to set the current picturebox (highlightedTileBox's) image to a scaled up version of the cropped image.
So I got a solution by trying around a bit.
It looks like scaling images directly by size is using some sort of interpolation.
To try different interpolation modes supported by Winforms, I created a little demo.
As you can see, every label contains the name of the InterpolationMode and is followed by its resulting image. The original bitmap I used is the small one at the top.
From your question, it looks like you would like to achieve something like NearestNeighbour.
Following code scales bmp and the result is stored in bmp2. Try if that's what you want. Consider building a proper implementation if you're using this as solution (disposing unused bitmaps etc.).
I hope it helps.
Bitmap bmp = new Bitmap("test.bmp");
Bitmap bmp2;
Graphics g = Graphics.FromImage(bmp2=new Bitmap(bmp.Width * 2, bmp.Height * 2));
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, 0, 0, bmp.Width * 2, bmp.Height * 2);
g.Dispose();

WPF: programatically draw a Rectangle to an ImageSource instance

I am new to C# and to WPF, and I could be looking at this completely wrong. I have a JPEG byte array as a source. I cannot change this. I need to get the array, perform some calculations and draw rectangles in areas of the JPEG. I then write it to an Image XAML control.
I get the JPEG and I can convert it into an ImageSource and display it to an ImageControl. I can't find a way to get the drawing context from the ImageSource. I use ImageSourceConverter to read in the JPEG array and this class returns an ImageSource instance, duh!.
ImageSource mImage = (ImageSource)mConverter.ConvertFrom(mImageBuffer);
ImageSource does not have a drawing context property.
What it seems like I need is a DrawingImage, it is derived from ImageSource and has a drawing context property.
How can I use a DrawingImage instead of the ImageSource.
I looked at the ImageDrawing class, it has an ImageSource property. This class doesn't have a drawing context.
I am currently looking into the Visual class, and help where to look would be appreciated.
Edit:
Thanks #nefarious for pointing me in the right direction. I ended with the following:
ImageSource mImage = (ImageSource)mConverter.ConvertFrom(mImageBuffer);
BitmapSource bImage = mImage as BitmapSource;
// Draw a Rectangle
DrawingVisual dVisual = new DrawingVisual();
using (DrawingContext dc = dVisual.RenderOpen())
{
dc.DrawImage(bImage, new Rect(0, 0, bImage.PixelWidth, bImage.PixelHeight));
dc.DrawRectangle(Brushes.Green, null, new Rect(20, 20, 150, 100));
}
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(640,480,96,96, PixelFormats.Default);
targetBitmap.Render(dVisual);
WriteableBitmap wBitmap = new WriteableBitmap(targetBitmap);
image.Source = wBitmap;
Have you looked at using Visuals, I don't know how efficient they are but it seems that you will be unable to copy the source into an ImageSource and draw directly into it.
Create a DrawingVisual and draw the ImageSource and the Rectangles into the drawing context of the drawing visual.
Then use WriteableBitmap to show it in the image;

Create WriteableBitmap from UIControl WPF

I am currently converting a Silverlight application into WPF. In my silverlight application I have the code
WriteableBitmap sceneBitmap = new WriteableBitmap(scene, new TranslateTransform() { Y = 10 });
WriteableBitmap newone = TimelineMainHelper.CropImage(sceneBitmap, 0, 0, sceneBitmap.PixelWidth, sceneBitmap.PixelHeight - 25);
newone.Invalidate();
img.Source = newone;
Where scene is a control.
When putting this into WPF there are no overloads for the writeablebitmap class which take UIElement and Transform as the parameters. Firstly I was wondering why this is? and secondly I was wondering if there was a way getting a control to a writeablebitmap
Instead you will want to use RenderTargetBitmap and CroppedBitmap I believe:
RenderTargetBitmap rtb = new RenderTargetBitmap((int)scene.ActualWidth, (int)scene.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
rtb.Render(this.sceneBitmap);
CroppedBitmap crop = new CroppedBitmap(sceneBitmap, new Int32Rect(0, 0, (int)sceneBitmap.ActualWidth, (int)sceneBitmap.ActualHeight));
Then you can do something like:
System.Windows.Controls.Image img = new Image();
img.Source = crop;
And go from there.
Disclaimer:
You may need to use different overloads and what not to do exactly what you wish. I just took a shot guessing what parameters to pass given your snippet.

How to save the painted control as a bitmap?

I have a picturebox (pictureBox1), and it gets lines drawn on it, from the paint event. I was wondering how to convert that drawing (with the lines) to a bitmap, and save it as a file. I've tried:
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox.Height);
pictureBox1.DrawToBitmap(bmp, pictureBox1.Bounds);
bmp.Save("MyImage.bmp");
But that is a blank image, without the lines. Does anyone know how I can save it with the lines? Thank you.
int bitmapX = 100
int bitmapY = 100
Bitmap imgToSave = new Bitmap(bitmapX, bitmapY);
Graphics gfx = Graphics.FromImage(imgToSave);
// draw on the image with
gfx.DrawLine() // or whatever you want to draw
// save the screenshot
string saveFilePath = Application.StartupPath + "\<name of the image>.png";
imgToSave.Save(saveFilePath, ImageFormat.Png);
This is a code snippet that works for me.
Don't use the PictureBox.Bounds property but instead use a simple Rectangle object/structure filled with the `PictureBox' width and height like this:
var bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bitmap, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
bitmap.Save("c:\\temp\\image.bmp");
Using the Bounds property you are fetching the correct size of the picture box control, but depending on the position not the 0,0 coordinate, but the control position, which leads to an empty bitmap.

text not showing on bitmap image in C#

I can't seem to get the text I've written to show up on my image Here's the code I'm using
//Creates a bitmap with the path to the current image
Bitmap LabelImage = new Bitmap(dtImages.Rows[intCurrentImage]["ImageURL"].ToString());
Graphics graphic = Graphics.FromImage(LabelImage);
graphic.DrawString("Hello", new Font("Tahoma",40), Brushes.Azure, new System.Drawing.Point(0,0));
//put Image that I just created and put the text on into an Infragistics UltraPicureBox
picImage.Image = LabelImage
You did not update your original image (LabelImage), so why should the text you added to the Graphics object show up?.
From MSDN, Graphics.FromImage:
Creates a new Graphics from the specified Image.
(emphasis mine)
After you have added the text, you need to save the changes:
graphic.Save();
Unrelated to your question, you should really put the creation of the Graphics object in a using statement, to ensure proper disposal:
using(Graphics graphic = Graphics.FromImage(LabelImage))
{
// use graphic here
}
I just tried this
Bitmap bitmap = new Bitmap("C:\\Untitled.png");
Graphics g = Graphics.FromImage(bitmap);
g.DrawString("Hello", new Font("Tahoma", 40), Brushes.Azure, new System.Drawing.Point(0, 0));
pictureBox1.Image = bitmap;
and it works fine for me. Just try to pick a contrasting brush.

Categories

Resources