How to save bmp (image) to file - c#

I want to Video File thumbnail. Get Video path and convert to Image. Then convert to bmp, and save the bmp as an image file. If this is possible, please show me a way.
private void add_Video_Image(string sFullname_Path_of_Video)
{
//*create mediaplayer in memory and jump to position
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.MediaOpened += new EventHandler(mediaplayer_OpenMedia);
mediaPlayer.ScrubbingEnabled = true;
mediaPlayer.Open(new Uri(sFullname_Path_of_Video));
mediaPlayer.Position = TimeSpan.FromSeconds(0);
}
private void mediaplayer_OpenMedia(object sender, EventArgs e)
{
MediaPlayer mediaPlayer = sender as MediaPlayer;
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawVideo(mediaPlayer, new Rect(0, 0, 160, 100));
drawingContext.Close();
double dpiX = 1 / 200;
double dpiY = 1 / 200;
RenderTargetBitmap bmp = new RenderTargetBitmap(160, 100, dpiX, dpiY, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
Image newImage = new Image();
newImage.Source = bmp;
newImage.Stretch = Stretch.Uniform;
newImage.Height = 100;
//save bmp to image
}

Please check this link. It holds the answer to your question: Easiest way of saving wpf Image control to a file
You can do the save prior to setting the 'RenderTargetBitmap' to the 'Image Control'.

Related

C# WPF Capture UI element to picture with white background

I need to capture UI element in this case LiveCharts chart and save it to a PNG/JPEG
I got this code
private void Button_Click(object sender, RoutedEventArgs e) {
var filePath = "qwerty.png";
var res = CaptureScreen(charts, charts.ActualWidth, charts.ActualHeight);
using (var fileStream = new FileStream(filePath, FileMode.Create)) {
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(res));
encoder.Save(fileStream);
}
}
private BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY) {
if (target == null) {
return null;
}
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen()) {
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), bounds.Size));
}
rtb.Render(dv);
return rtb;
}
I can get a png no problem. Though it is the picture created is 30k x 9k pixels. The picture has a transparent background. what would be the best practice to capture a UI element and export as a picture with a white backgroun?

how to have my rectangle always on the middle of the image without knowing the size of the incomming image

Trying to add a watermark image to a png image, i´ve been able to do it, but i want to take out the hardCoded size regulation for the rectangle of the waterMark, and make it always stay in the center of the image. How can i achieve this.
public Form1()
{
InitializeComponent();
picBox.Parent = this;
picBox.Dock = DockStyle.Fill;
picBox.SizeMode = PictureBoxSizeMode.Zoom;
Bitmap Jpg = new Bitmap(#"C:\Users\tferreira\Desktop\213123.PNG");
using (Bitmap Bmp = new Bitmap(#"C:\Users\tferreira\Desktop\logo.png"))
{
using (Bitmap WatermarkBmp = new Bitmap(Bmp, Bmp.Width / 1, Bmp.Height / 1))
{
picBox.Image = WatermarkImage(Jpg, WatermarkBmp, new Point(400, 100), 0.40F);
}
}
}
public Bitmap WatermarkImage(Bitmap ImageToWatermark, Bitmap Watermark, Point WatermarkPosition, float Opacity)
{
using (Graphics G = Graphics.FromImage(ImageToWatermark))
{
using (ImageAttributes IA = new ImageAttributes())
{
ColorMatrix CM = new ColorMatrix();
CM.Matrix33 = Opacity;
IA.SetColorMatrix(CM);
G.DrawImage(Watermark, new Rectangle(WatermarkPosition, Watermark.Size), 0, 0, Watermark.Width, Watermark.Height, GraphicsUnit.Pixel, IA);
}
}
return ImageToWatermark;
}
Right now the images are hardCoded but that will be taken out. If anyone can help me make this watermark allways stay centered i thank you.
I fixed this problem with this nice peace of code.
System.Drawing.Image img = System.Drawing.Image.FromFile(JpgFilePath);
Bitmap jpg = new Bitmap(img);
filePath = JpgFilePath;
int Width = jpg.Width;
int Height = jpg.Height;
jpg.SetResolution(300, 300);
WaterMarked = WatermarkImage(jpg, WaterMarkBit, new Point((Width - WaterMarkBit.Width) / 2, (Height - WaterMarkBit.Height) / 2), 0.4F);
WaterMarked.Save(filePath.Replace(".jpg", "") + ".tif", ImageFormat.Tiff);
filesJpgForTif.Add(JpgFilePath.Replace("jpg", "tif"));
Using the the sizes of the image and sizes of the watermark and divide it by 2 it makes the image always stay centered.

Saving image from inkCanvas as png or jpeg file

Here is my wpf code
<InkCanvas x:Name="inkCanvas" Margin="9,325,210,193" Background="Azure"></InkCanvas>
And also there is a button
When pressing the button, i want to save image drawn to a file. here is my code
private void button1_Click(object sender, RoutedEventArgs e)
{
int margin = (int)inkCanvas.Margin.Left;
int width = (int)inkCanvas.ActualWidth - margin;
int height = (int)inkCanvas.ActualHeight - margin;
RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
rtb.Render(inkCanvas);
using (FileStream fs = new FileStream("path", FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(fs);
}
}
But image dusplayed is all black (whatching from an explorer) or complitely white, if opened in paint.
What do i do to get an image exactely as drawn? ty.
The problem is that you are trying to save Vector Graphics as a Bitmap and thats not possible, so first what you need to do is draw the Vectors and then you can save the Drawing
this class will draw Ink on to a existing bitmap
public class InkImage
{
public static BitmapFrame MergeInk(StrokeCollection ink, BitmapSource background)
{
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawImage(background, new Rect(0, 0, background.Width, background.Height));
foreach (var item in ink)
{
item.Draw(drawingContext);
}
drawingContext.Close();
var bitmap = new RenderTargetBitmap((int)background.Width, (int)background.Height, background.DpiX, background.DpiY, PixelFormats.Pbgra32);
bitmap.Render(drawingVisual);
return BitmapFrame.Create(bitmap);
}
}
}
you can then save the bitmap using the JPEG or PNG encoder

Exporting a code-created Steema chart with custom image

Is there some way to export a Steema Chart with custom drawings without passing a "screen draw"?
I'm trying to export a Steema TChart that hasn't been drawn on screen with some custom drawings on it. I found the Graphics3D object, but when I try to use it it throws a NullReferenceException :
at Steema.TeeChart.WPF.Drawing.Graphics3DWPF.Draw(Rect destRect, Rect srcRect, BitmapSource image, Boolean transparent)
at Steema.TeeChart.WPF.Drawing.Graphics3D.Draw(Rect r, BitmapSource image, Boolean transparent)
at WpfSteemaApplication.MainWindowViewModel.SaveImage() ...
The only other information regarding custom drawing I have found is in the events BeginDraw and AfterDraw, which doesn't seem to be called before I export my image.
However, everything else seems to render just fine, it's just my custom image that I need as well.
private void SaveImage()
{
BitmapSource bitmap = new BitmapImage(new Uri("pack://application:,,,/button.png"));
TChart chart = new TChart();
JPEGFormat jpegFormat = chart.Export.Image.JPEG;
// This throws an exception when uncommented.
//chart.Graphics3D.Draw(new Rect(0, 0, 100, 100), bitmap, true);
Line line = new Line();
line.FillSampleValues();
chart.Series.Add(line);
jpegFormat.Width = 1024;
jpegFormat.Height = 340;
jpegFormat.Quality = 100;
jpegFormat.Save("C:\\Temp\\steemachart.jpg");
}
I found the DoInvalidate() method on the chart which in turn calls AfterDraw. When exporting the image after that both the image and the chart is rendered in the image
private void SaveImage()
{
TChart chart = new TChart();
JPEGFormat jpegFormat = chart.Export.Image.JPEG;
Line line = new Line();
line.FillSampleValues();
chart.Series.Add(line);
jpegFormat.Width = 1024;
jpegFormat.Height = 340;
jpegFormat.Quality = 100;
chart.AfterDraw += OnAfterDraw;
chart.DoInvalidate();
jpegFormat.Save("C:\\Temp\\steemachart.jpg");
}
private void OnAfterDraw(object sender, Graphics3D g)
{
BitmapSource bitmap = new BitmapImage(new Uri("pack://application:,,,/button.png"));
g.Draw(new Rect(0, 0, bitmap.Width, bitmap.Height), bitmap, true);
}

How do I print an Image from a Uri?

I am attempting to print a JPEG file that I reference using a Uri object and am having some difficulties. I found that while the image was printing, it was cropped slightly and was flipped and mirrored. I'm guessing that the crop was caused by a size not being set properly but have no idea why it's being flipped and rotated. Assuming that this was a natural oddity, I attempted to resolve the issue by applying a transform to the drawingContext object but this results a blank page being printed. Here is my code:
public void Print(List<Uri> ListToBePrinted)
{
XpsDocumentWriter writer =
PrintQueue.CreateXpsDocumentWriter(this.SelectedPrinter.PrintQueue);
PrintCapabilities printerCapabilities =
this.SelectedPrinter.PrintQueue.GetPrintCapabilities();
Size PageSize =
new Size(printerCapabilities.PageImageableArea.ExtentWidth,
printerCapabilities.PageImageableArea.ExtentHeight);
foreach (Uri aUri in ListToBePrinted)
{
BitmapImage anImage = new BitmapImage(aUri);
//create new visual which would be initialized by image
DrawingVisual drawingVisual = new DrawingVisual();
//create a drawing context so that image can be rendered to print
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Flips along X and Y axis (flips and mirrors)
drawingContext.PushTransform(new ScaleTransform(-1, -1));
drawingContext.DrawImage(anImage, new Rect(PageSize));
drawingContext.Close();
writer.Write(drawingVisual);
}
}
Any help would be greatly appreciated - thank you!
Here's what I ended up with:
public void Print(List<Uri> ListToBePrinted)
{
XpsDocumentWriter writer =
PrintQueue.CreateXpsDocumentWriter(this.SelectedPrinter.PrintQueue);
PrintCapabilities printerCapabilities =
this.SelectedPrinter.PrintQueue.GetPrintCapabilities();
Size PrintableImageSize =
new Size(printerCapabilities.PageImageableArea.ExtentWidth,
printerCapabilities.PageImageableArea.ExtentHeight);
foreach (Uri aUri in ListToBePrinted)
{
DrawingVisual drawVisual = new DrawingVisual();
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(aUri);
imageBrush.Stretch = Stretch.Fill;
imageBrush.TileMode = TileMode.None;
imageBrush.AlignmentX = AlignmentX.Center;
imageBrush.AlignmentY = AlignmentY.Center;
using (DrawingContext drawingContext = drawVisual.RenderOpen())
{
// Flips along X and Y axis (flips and mirrors)
drawingContext.PushTransform(new ScaleTransform(-1, 1, PrintableImageSize.Width / 2, PrintableImageSize.Height / 2));
drawingContext.PushTransform(new RotateTransform(180, PrintableImageSize.Width / 2, PrintableImageSize.Height / 2)); // Rotates 180 degree
drawingContext.DrawRectangle(imageBrush, null, new Rect(25, -25, PrintableImageSize.Width, PrintableImageSize.Height));
}
writer.Write(drawVisual);
}
}
The image is a little fuzzy but is certainly acceptable. I'm still not sure why my image needed to be flipped or mirrored.
Could you do something like:
BitmapImage anImage = new BitmapImage(aUri);
Image image = new Image();
image.BeginInit();
image.Source = anImage;
image.EndInit();
image.Measure(PageSize);
image.InvalidateVisual();
Then just print the Image object since it derives from Visual...
You need to call InvalidateVisual so that OnRender will be called, if you didn't it would result in a blank image...

Categories

Resources