Printing bitmap from Silverlight - image blurry - c#

I'm trying to print image from Silverlight application. I have pretty good quality scans (TIFF) with resolution 1696x2200
When I print - I get PrintableArea from PrintDocument and it's 816x1056
What I do - I resize bitmap to Printable area (to fit document to page) and result I get is blurry image. I understand this is scaling problem (most likely), but how do I scale properly so it looks good? When I display document inside Image and just set image size - it looks good.
For resizing I'm using WriteableBitmapEx extensions and tried both types of resize (Nearest neighbor and bilinear)
Code:
var printDocument = new PrintDocument();
printDocument.PrintPage += (s, ea) =>
{
var printableArea = ea.PrintableArea;
var bitmap = this.currentPreviewPage.FullBitmap.Resize((int)printableArea.Width, (int)printableArea.Height, WriteableBitmapExtensions.Interpolation.Bilinear);
var image = new Image { Source = bitmap };
var canvas = new Canvas { Width = bitmap.PixelWidth, Height = bitmap.PixelHeight };
canvas.Children.Add(image);
ea.PageVisual = canvas;
ea.HasMorePages = false;
};
printDocument.PrintBitmap("Silverlight Bitmap Print");
How document looks on screen (inside Image)
And this is printed:

Rather than using the WriteableBitmapEx extensions, when declaring your Image element, try setting the Stretch property so that it stretches based on your maximum specified dimensions:
var image = new Image { Source = bitmap, Stretch = Stretch.UniformToFill };

Blilinear filter tends to blur images.You may want to try WriteableBitmapExtensions.Interpolation.NearestNeighbor instead to see if you get better results

In my case it was enough to set UseLayoutRounding="True".

Related

Crop a svg image and convert it to png

I have a big svg image.
I would like to crop it to a rectangle, using coordinates, and convert it to png image.
I have to say that I'm not used to drawing with c#.
Surface, Canvas and other notions are new to me.
I have figured out how to load the svg, using SkiaShark and SkiaShark.Svg:
var svg = new SkiaSharp.Extended.Svg.SKSvg();
svg.Load(tmpPath);
And found a gist that saves a png. But this is "Chinese" for me.
var imageInfo = new SKImageInfo(100, 100);
using (var surface = SKSurface.Create(imageInfo))
using (var canvas = surface.Canvas)
{
// calculate the scaling need to fit to screen
var scaleX = 100 / svg.Picture.CullRect.Width;
var scaleY = 100 / svg.Picture.CullRect.Height;
var matrix = SKMatrix.CreateScale((float)scaleX, (float)scaleY);
// draw the svg
canvas.Clear(SKColors.Transparent);
canvas.DrawPicture(svg.Picture, ref matrix);
canvas.Flush();
using (var data = surface.Snapshot())
using (var pngImage = data.Encode(SKEncodedImageFormat.Png, 100))
{
tmpPath = Path.ChangeExtension(tmpPath, "PNG");
using var imageStream = new FileStream(tmpPath, FileMode.Create);
pngImage.SaveTo(imageStream);
}
}
If someone could show me the directions, it would be much appreciated.
EDIT
I've come to this implentation myself, though it is not working... The result bitmap is transparent and empty.
private string ConvertSVGToPNGRectangleWithSkiaSharpExtended(string path, double left, double top, double right, double bottom)
{
var svg = new SkiaSharp.Extended.Svg.SKSvg();
var picture = svg.Load(path);
// Get the initial map size
var source = new SKRect(picture.CullRect.Left, picture.CullRect.Top, picture.CullRect.Width, picture.CullRect.Height);
// Cropping Rect
var cropRect = new SKRect((int)left, (int)top, (int)right, (int)bottom);
var croppedBitmap = new SKBitmap((int)cropRect.Width, (int)cropRect.Height);
using var canvas = new SKCanvas(croppedBitmap);
canvas.Clear(SKColors.Transparent);
canvas.DrawBitmap(croppedBitmap, source, cropRect);
var data = croppedBitmap.Encode(SKEncodedImageFormat.Png, 100);
path = Path.ChangeExtension(path, "PNG");
using var imageStream = new FileStream(path, FileMode.Create);
data.SaveTo(imageStream);
return path;
}
EDIT 2:
I'm sorry , if it is not clear. You can refer to this question for doing so on Android.
Disclaimer: I'm not an expert with SkiaSharp, but I do know about drawing and canvases and I looked up the documentation at https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skcanvas.drawpicture
I think the problem is this line:
canvas.DrawBitmap(croppedBitmap, source, cropRect);
I think you need:
canvas.DrawPicture(picture, -cropRect.Left, -cropRect.Top);
canvas.Flush();
I might have the coordinates wrong, but the problem behind your failure is that you are never drawing picture to the canvas.
To help with your confusion about what a canvas is: SKCanvas(croppedBitmap) is making it so that every time you draw to canvas, what you are actually drawing on is the bitmap. So in order to draw your picture onto the bitmap, you have to draw picture onto canvas. Using negative coordinates make it so the top and left of the svg picture are above and to the left of the top-left corner of the bitmap, which is the equivalent of having the bitmap start somewhere in the middle of the svg picture.
Hope this helps!

Display videoframe and RenderTargetBitmap position

I'm trying to crop an image from webcam and display right next to the camera preview.
Cropping an image should be carried with 3 considerations.
Output of cropped image should be in form of VideoFrame
The above output, VideoFrame, needs to be displayed (on XAML)
The target crop image is in the middle of original image
I found RenderTargetBitmap would help me to get an cropped image.
But still I have no idea how to display VideoFrame (without saving an image), set the position where to crop.
I got stuck below...
public async Task<VideoFrame> CroppingImage(Grid grid)
{
RenderTargetBitmap renderBitmap = new RenderTargetBitmap();
await renderBitmap.RenderAsync(grid);
var buffer = await renderBitmap.GetPixelsAsync();
var softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, renderBitmap.PixelWidth, renderBitmap.PixelHeight, BitmapAlphaMode.Ignore);
buffer = null;
renderBitmap = null;
VideoFrame vf = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
await CropAndDisplayInputImageAsync(vf);
return cropped_vf;
}
private async Task CropAndDisplayInputImageAsync(VideoFrame inputVideoFrame)
{
//some cropping algorithm here
//i have a rectangle on a canvas(camera preview is on CaptureElement)
//I know the left top position and width and height but no idea how to use
}
Any help?
This is what i found and done :)
(assume that there is a videoframe which name is croppedface)
croppedFace = new VideoFrame(BitmapPixelFormat.Bgra8, (int)width, (int)height, BitmapAlphaMode.Ignore);
await inputVideoFrame.CopyToAsync(croppedFace, cropBounds, null);
SoftwareBitmap asdf = croppedFace.SoftwareBitmap;
asdf = SoftwareBitmap.Convert(asdf, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
var qwer = new SoftwareBitmapSource();
await qwer.SetBitmapAsync(asdf);
CroppedFaceImage.Source = qwer;
But still I have no idea how to display VideoFrame(without saving an image), set the position where to crop.
If you want to show the frame on the xaml, you need to convert the frame to a displayable format and rendering it to the screen. Please check the FrameRender class in the official Camera frames sample. It has a ConvertToDisplayableImage method that should be what you want.
Then, you could show it in Image control. After that, you could use Image.Clip to set the position where you want to crop.

how to extend draw area in Graphics.DrawImage c#

I have a Rectangle (rec) that contains the area in which a smaller image is contained within a larger image. I want to display this smaller image on a Picturebox. However, what I really am doing is using the smaller image as a picture detector for a larger image that is 333x324. So what I want to do is use the coordinates of the smaller image rectangle, and then draw to the Picturebox, starting from lefthand side of the rectangle, going outwards by 333 width and 324 height.
Currently my code works but it only displays the small image that was being used for detection purposes. I want it to display the smaller image + 300 width and + 300 height.
I fiddled with this code for hours and I must be doing something extremely basic wrong. If anyone can help me I would appreciate it so much!
My code for the class:
public static class Worker
{
public static void doWork(object myForm)
{
//infinitely search for maps
for (;;)
{
//match type signature for Threading
var myForm1 = (Form1)myForm;
//capture screen
Bitmap currentBitmap = new Bitmap(CaptureScreen.capture());
//detect map
Detector detector = new Detector();
Rectangle rec = detector.searchBitmap(currentBitmap, 0.1);
//if it actually found something
if(rec.Width != 0)
{
// Create the new bitmap and associated graphics object
Bitmap bmp = new Bitmap(rec.X, rec.Y);
Graphics g = Graphics.FromImage(bmp);
// Draw the specified section of the source bitmap to the new one
g.DrawImage(currentBitmap, 0,0, rec, GraphicsUnit.Pixel);
// send to the picture box &refresh;
myForm1.Invoke(new Action(() =>
{
myForm1.getPicturebox().Image = bmp;
myForm1.getPicturebox().Refresh();
myForm1.Update();
}));
// Clean up
g.Dispose();
bmp.Dispose();
}
//kill
currentBitmap.Dispose();
//do 10 times per second
System.Threading.Thread.Sleep(100);
}
}
}
If I understand correctly, the rec variable contains a rectangle with correct X and Y which identifies a rectangle with Width=333 and Height=324.
So inside the if statement, start by setting the desired size:
rec.Width = 333;
rec.Height = 324;
Then, note that the Bitmap constructor expects the width and height, so change
Bitmap bmp = new Bitmap(rec.X, rec.Y);
to
Bitmap bmp = new Bitmap(rec.Width, rec.Height);
and that's it - the rest of the code can stay the way it is now.

Change bg image relative to screen c# winforms

Here's what I have:
var rand = new Random();
var files = Directory.GetFiles("C:/Projects/MOMENTUM/MOMENTUM/pics/", "*.jpg");
Image bgimage = new Bitmap(files[rand.Next(files.Length)]);
BackgroundImage = bgimage;
Rectangle UsedScreen = Screen.FromControl(this).Bounds;
if (UsedScreen.Height / UsedScreen.Width > bgimage.Height / bgimage.Width)
{
//SET IMAGE HEIGHT TO SCREEN HEIGHT
}
else
{
//SET IMAGE WIDTH TO SCREEN WIDTH
}
As you see, I first choose a random image from a specific folder and then set this as background image.
I want this application to run in full screen. However, if i set the bgimage ImageLayout property to Zoom, there will be this ugly borders and if I set it to stretch, it will look awful.
I want to achieve the following:
I get the current used screensize via screen bounds, and then adjust the image to fit the screen without being distorted.
Part of the image will be cut away but the main aim is, that the entire screen is always filled out by the image (See the comments in if). I don't know how to do this because if I try
bgimage.Height = UsedScreen.Height
I cant overwrite the image height.
Any ideas?

image quality is blurry

I have a situation where I want to convert some XAML to an image, so I created a RichTextBox and then took the image of it. Now problem is that words in image is blurred, any idea how I might be able to fix it?
public System.Drawing.Bitmap ConvertXamltoImage(string XamlString, int Width, int Height)
{
RichTextBox AdContentRichTextBox = new RichTextBox() { Width = Width, Height = Height };
AdContentRichTextBox.BorderThickness = new Thickness(0);
XmlReader _XmlReader = XmlReader.Create(new StringReader(XamlString));
AdContentRichTextBox.Document = XamlString;
var size = new Size(Width, Height);
AdContentRichTextBox.Measure(size);
AdContentRichTextBox.Arrange(new Rect(size));
RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 300, 300, PixelFormats.Pbgra32);
bmp.Render(AdContentRichTextBox);
DrawingVisual _drawingVisual = new DrawingVisual();
using (DrawingContext _drwaingContext = _drawingVisual.RenderOpen())
{
VisualBrush _visualBrush = new VisualBrush(AdContentRichTextBox);
}
PngBitmapEncoder _png = new PngBitmapEncoder();
_png.Frames.Add(BitmapFrame.Create(bmp));
System.Drawing.Bitmap _tempBitmap = null;
using (Stream _fileStream = new MemoryStream())
{
_png.Save(_fileStream);
_tempBitmap = new System.Drawing.Bitmap(_fileStream);
_fileStream.Flush();
}
return _tempBitmap;
}
Hmmmm..there could be lots of things all interacting here:
1st
"Grayscale fall back - if ClearType is disabled or one is rendering text in certain situations where the ClearType algorithm cannot be run, WPF will use a grayscale rendering algorithm to antialias the rendered text."
Rendering Text to a RenderTargetBitmap seems to be one of those situations....(the renderer switches from a hardware to a software path).
2nd
In addition NET 4 switched the default scaling algorithm from high-quality (Fant) to low-quality (Bi-Linear).....now that shouldn't come into play here as it doesn't look like you are scaling the bitmap in any way...but you never know what's going on inside. It's possible to switch the scaler back to the higher quality one.
http://www.olsonsoft.com/blogs/stefanolson/post/Workaround-for-low-quality-bitmap-resizing-in-WPF-4.aspx
3rd
You may need to take into account the parent container of the RichTextBox...see last link below, mentions it can distort the font rendering.
Problems with rendering text as bitmaps using WPF
Some ideas on how to work around this are:
render the RichTextBox at a higher resolution e.g. 600dpi, and then scale down the bitmap (probably will make no difference)
capture the screen....difficult or not practical if your visual is offscreen/obscured, etc.
See related links:
http://windowsclient.net/wpf/white-papers/wpftextclarity.aspx
WPF RenderTargetBitmap downscaling text ClearType to GreyScale
WPF RenderTargetBitmap downscaling TextRenderMode to GreyScale
WPF text rendering inconsistencies

Categories

Resources