While testing in the samples from PDFPrintTest, we noticed that Example 2 coupled with Event Handler's example 1 is not behaving properly.
Example 1 of PrintPage Event Handler:
void PrintPage(object sender, PrintPageEventArgs ev)
{
Graphics gr = ev.Graphics;
gr.PageUnit = GraphicsUnit.Inch;
Rectangle rectPage = ev.PageBounds; //print without margins
//Rectangle rectPage = ev.MarginBounds; //print using margins
float dpi = gr.DpiX;
if (dpi > 300) dpi = 300;
int example = 1;
bool use_hard_margins = false;
// Example 1) Print the Bitmap.
if (example == 1)
{
pdfdraw.SetDPI(dpi);
Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current());
//bmp.Save("tiger.jpg");
gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
}
Full sample code here: https://www.pdftron.com/pdfnet/samplecode/PDFPrintTest.cs.html
You'll notice the bmp.Save("tiger.jpg"); in comment, that's the point where it goes wrong. If we run the code and save the bmp, we get exactly what we need in the jpg file. However, gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel); prints a plain empty pdf page. Why is that ?
Our goal: We need to force a printjob with 40% grayscale in certain circumstances. Winforms does not support this, we can only set grayscale, not specify a percentage, so we are looking to intercept the print and change the output to 40% grayscale, which lead us to the PdfNet Print samples. From these samples, only example 2 in the handler has Graphics gr which accepts a color matrix to set the wanted grayscale to the page.
Any non-PdfNet solution is welcome aswell, but it's still odd that the sample code isn't working out of the box.
Thank you for pointing this out. Just as you are, I am unclear why bmp.Save works fine, but Graphics.DrawImage(bmp,... is only showing the background color. I suspect it has something to do with the other parameters passed into Graphics.DrawImage
Since the Bitmap object is correct, then this particular issue is really a .Net question and not a PDFNet question, which I am currently unable to answer.
The other part of the sample runs fine, the one using PDFDraw.DrawInRect. Does this not work for you?
We got it working, apparently it was only giving a white page when printing to pdf. The exact same code rendered a much too small image but actually printed.
We're still not entirely sure what the issue was, but worked out new code that properly prints to pdf, and prints full-scale to a printer.
void PrintPage(object sender, PrintPageEventArgs ev)
{
Graphics gr = ev.Graphics;
gr.PageUnit = GraphicsUnit.Pixel; //this has been changed to Pixel, from Inch.
float dpi = gr.DpiX;
//if (dpi > 300) dpi = 300;
Rectangle rectPage = ev.PageBounds; //print without margins
//Rectangle rectPage = ev.MarginBounds; //print using margins
float dpi = gr.DpiX;
int example = 1;
bool use_hard_margins = false;
// Example 1) Print the Bitmap.
if (example == 1)
{
pdfdraw.SetDPI(dpi);
pdfdraw.SetDrawAnnotations(false);
Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current());
gr.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
}
`
if (dpi > 300) dpi = 300; This was the main culprit in rendering a too small image being sent to the printer. It also fixed the 'white pdf' issue.
Second, we didn't pass rectPage to DrawImage, and replaced it with: new Rectangle(0, 0, bmp.Width, bmp.Height).
I can understand the smaller size being sent to the printer, but why it didn't pick up anything to print to pdf is still unclear.
While the ultimate goal is still printing, it's much easier to debug and test with a properly working 'print to pdf'. The above code works in 2 separate projects, so I'm going to assume this indeed fixes the issue.
Related
What I'm trying to do:
Since in my bitmaps there are some unwanted white edges around the picture that result from anti-aliasing as pointed out from another user from stackoverflow.
I'm trying to convert an image that's inputted into a bitmap, convert bitmap into a Graphics object so that I can set the Smooth Mode to none, and then finally convert that Graphics object to a bitmap so that it can be copied by the user after setting it to the clipboard. I'm not sure if this is a good way of getting rid anti-aliasing in bitmaps but I'm definitely interested in improvements and suggestions.
The issue I'm facing:
The result of the image after is completely blank and does not contain any of the pixels that are previously found in the original bitmap. Here's the result:
This issue applies to all pictures no matter what their format is.
My code:
public PicGen(PictureBox pictureBox)
{
Clipboard.Clear();
Bitmap firstImage = new(pictureBox.Image, pictureBox.Width, pictureBox.Height);
RectangleF cloneRect = new RectangleF(0, 0, firstImage.Width, firstImage.Height);
System.Drawing.Imaging.PixelFormat format = firstImage.PixelFormat;
Bitmap cloneBitmap = firstImage.Clone(cloneRect, format);
Graphics AntiARemover = Graphics.FromImage(cloneBitmap);
AntiARemover.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
Bitmap finalImg = new(52, 52, AntiARemover);
Clipboard.SetImage(finalImg);
Color backColorBottom = firstImage.GetPixel(0, 0);
firstImage.ReplaceColor(backColorBottom, Color.FromArgb(54, 57, 63));
Bitmap finalImg = new(52, 52, AntiARemover);
From the documentation for this bitmap constructor:
The new Bitmap that this method creates takes its horizontal and vertical resolution from the DpiX and DpiY properties of g, respectively.
If you want create a new image with the content from another you need to call one of the DrawImage methods. You should also dispose your graphics object, and any temporary bitmaps you may use.
using var finalImg = new Bitmap(52,52);
using var graphics = Graphics.FromImage(finalImg);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
graphics.DrawImage(cloneBitmap)
However, edge artifacts typically occur when combining two images using an alpha channel, see Premultiplied alpha. In your example I can only see one input image, so I'm really not sure what it is you are actually trying to do. If you need to convert to premultiplied alpha you can use the following code to convert the color for each pixel
premultiplied.R = (byte)(straight.R * straight.A / 255);
premultiplied.G = (byte)(straight.G * straight.A / 255);
premultiplied.B = (byte)(straight.B * straight.A / 255);
premultiplied.A = straight.A;
I have a project in which I create an image with rotated text around an invisible circle.
The drawing in itself is working just fine. However, it seems that no matter the font I use, I always get the same result, which is I assume some low quality default font.
Here is the code :
Bitmap objBmpImage = new Bitmap(1000, 1000);
System.Drawing.Text.InstalledFontCollection installedFontCollection = new System.Drawing.Text.InstalledFontCollection();
FontFamily[] fontFamilies = installedFontCollection.Families;
System.Drawing.Font objFont = new System.Drawing.Font(fontFamilies.Where(x => x.Name == "Arial").FirstOrDefault(),10);
Graphics objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.Transparent);
float angle = (float)360.0 / (float)competences.Count();
objGraphics.TranslateTransform(500, 450);
objGraphics.RotateTransform(-90 - (angle / 3));
int nbComptetence = competences.Count();
int indexCompetence = 0;
foreach (T_Ref_Competence competence in competences)
{
byte r, g, b;
HexToInt(competence.T_Ref_CompetenceNiveau2.T_Ref_CompetenceNiveau1.Couleur, out r, out g, out b);
Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(255,r,g,b));
if (indexCompetence * 2 < nbComptetence)
{
objGraphics.DrawString(competence.Nom, objFont, brush, 255, 0);
objGraphics.RotateTransform(angle);
}
else
{
objGraphics.RotateTransform(180);
objGraphics.RotateTransform(angle/2);
float textSize = objGraphics.MeasureString(competence.Nom, objFont).Width;
objGraphics.DrawString(competence.Nom, objFont, brush, -253 - textSize, 0);
objGraphics.RotateTransform(angle);
objGraphics.RotateTransform(-180);
objGraphics.RotateTransform(-angle / 2);
}
indexCompetence++;
}
I get the font using the installed families like this
System.Drawing.Text.InstalledFontCollection installedFontCollection = new System.Drawing.Text.InstalledFontCollection();
FontFamily[] fontFamilies = installedFontCollection.Families;
System.Drawing.Font objFont = new System.Drawing.Font(fontFamilies.Where(x => x.Name == "Arial").FirstOrDefault(),10);
I tried using other font but the result is always the same. Is there anything I am missing ? If not, what could be the reason ?
Thanks,
EDIT : To answer the question, what is it that I want exactly, consider this :
This image is a screenshot of a web site I am making. The chart in the middle was generated using charts.js, but its limitation force me to draw the text as a background image. It actually takes most of my screen so it can't really get much bigger than this. As you can see, the text font is pretty blurry and I would simply want it to be easier to read. I though the font was the problem, but I don't really know.
I am not really familiar with the whole image drawing part of C#, so if there are is better way to draw my text (which can change depending of many variables), I will gladly try other things.
Option 1: change text rendering
objGraphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel
Option 2: change the mode of anti aliasing
objGraphics.InterpolationMode=InterpolationMode.NearestNeighbor;
Option 3: change the DPI of the image
You'll get the best result if you scale the input image and then draw the text in higher DPI.
The default DPI for a Bitmap are 96. Probably the JS library exported with that setting.
If you want a smoother rendering of the font, you need to increase the DPI, e.g.
objBmpImage.SetResolution(1200,1200);
If you do so, you probably need to increase the number of pixels your Bitmap has.
If the "ugly" text just fitted the 1000x1000 picture, you now need 1000*1200/96=12500 pixels.
Before the change (using Arial 10 pt):
After the change (still using Arial 10 pt):
Note that the size in centimeters doesn't change. So it will still print well.
I need to shrink multiple images that contain text. Because of the text they need to be shrunk in such a way as to retain the sharp edges of the text and not smoothed. My first attempt was the following:
RenderOptions.SetBitmapScalingMode(upgradeCard, BitmapScalingMode.HighQuality);
upgradeCard.Height(resizedHeight);
upgradeCard.Width(resizedWidth);
The result was too blurry, the text was hard to read. It was, however, really really fast. I then tried this:
public static class ImageResizer
{
public static Image Resize(Image image, Size size)
{
if (image == null || size.IsEmpty)
return null;
var resizedImage = new Bitmap(size.Width, size.Height, image.PixelFormat);
resizedImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(resizedImage))
{
var location = new Point(0, 0);
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.None;
graphics.DrawImage(image, new Rectangle(location, size),
new Rectangle(location, image.Size), GraphicsUnit.Pixel);
}
return resizedImage;
}
}
This worked really well, almost as good as Photoshop Bicubic Sharper. Unfortunately it was also very slow. Way too slow for what I need.
Is there any other way of doing this that produces the results of the second method but does so fairly quickly?
Without examples of your images it's hard to give reliable advice.
For example, how much contrast is in your images already? By what factor are you reducing them?
You could try nearest neighbour scaling, which can be very fast, and then try blurring the output slightly with a Gaussian filter, or similar. If that's too aliased, you could also try linear scaling with a soft blur.
I am trying to capture a part of my screen.
The problem is even if I use png to save the image the quality still worse than if I would just use normal print screen.
Here is the code I use:
//display a save file dialog for the user to set the file name
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "PNG (*.png)|*.png";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
//if the user proceed saving the picture
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//simplify code with constant numbers for demo
//get the width of the panel we need the screenshoot off
int x = 10;
//get the height of the panel we need the screenshoot off
int y = 10;
//create the ractangle of the screenshoot panel
Rectangle rect = new Rectangle(x, y, 5, 5);
//create new bitmap
Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
//get the screenshoot of the panel
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
string fileName = saveFileDialog.FileName;
if (!fileName.Contains(".png"))
fileName += ".png";
bmp.Save(fileName, ImageFormat.Png);
}
EDIT:
Example image form what I take with code:
Normal screenshot:
It does not look so different here, but it is worst.
The top image in your question was rescaled, smaller than the original. This is noticeable in images that contain fine detail, like the ClearType anti-aliasing pixels used to make the text more readable. When they get rescaled, the visual effect is ruined and text looks a lot worse.
It is entirely unclear why the image was rescaled, nothing in your code could cause that. Double-check by using the debugger to inspect the bmp.HorizontalResolution property, it should match the DPI of your video adapter. Simplest explanation that it was done by whatever image viewing program you used, perhaps to make the image fit the window. Try zooming out.
If it's possible to use a external library I suggest you FMUtils.Screenshot. Its available as a NuGet-package.
I just tried it and the quality is like the standard screenshot from windows. Here's a shortexample:
new ComposedScreenshot(new Rectangle(0, 0, 100, 100)).ComposedScreenshotImage.Save(#"PATH_TO_FILE\example-screenshot.png", ImageFormat.Png);
Hope this helps!
The pixel format you use only uses 8 bits each for the different color channels. You could try using PixelFormat64bppARGB to get 16 bits per color.
Resource on the PixelFormat enumeration: http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat%28v=vs.110%29.aspx
Since I've tried to draw string with every combination of smoothing and rendering with Graphics.DrawString() I was thinking that text renderer would do a better job drawing my strings but I think was wrong.
This is how it is supposed to look like:
And this is how it looks like:
Here is my code:
Graphics objGraphics2 = Graphics.FromImage(objBitmap);
objGraphics2.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
objGraphics2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
objGraphics2.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
objGraphics2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
Font textFont = new Font(textFontFamily, PxtoEm(textSize));
SolidBrush b = new SolidBrush(textColor);
TextRenderer.DrawText(objGraphics2, textValue, textFont, new Rectangle(0, 0, Width, Height), textColor);
Is my PxtoEm method wrong?
public float PxtoEm(int px)
{
float em = (float)(Convert.ToDouble(Convert.ToDouble(px) * Convert.ToDouble(72) / Convert.ToDouble(objBitmap.HorizontalResolution)));
return em;
}
I need some suggestions because this is really awful, it gets worse with larger fonts and images aren't shrunk.
UPDATE: Got it working with bigger fonts(ie. 20px) but with smaller fonts it gets kind of erased on some letters:
This is how it's suposed to be with font Arial 10px:
This is result with Graphics.DrawString()
As you can see it really isn't very good but closest I got. I made some changes to code and got better results with larger font:
This is how it's suposed to be with font Arial 20px:
This is drawing result:
And here is the changed code(I droped em method and used pixels directly, switched to Graphics.DrawString() instead of TextRenderer.DrawText()
Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
objGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
objGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
Font textFont = new Font(textFontFamily, textSize,GraphicsUnit.Pixel);
SolidBrush b = new SolidBrush(textColor);
PointF origin = new PointF((float)TextLeft,(float)TextTop);
StringFormat format = StringFormat.GenericTypographic;
objGraphics.DrawString(textValue, textFont, b , origin, format);
If someone has some suggestion to maybe write different method for smaller text sizes and use above code for larger as it works nicely, post it and I'll try it!
UPDATE 3: Finally found solution for everything, and solution was rather simple:
DON'T USE TRANSPARENT BACKGROUND!
And settings are:
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; // <-- important!
objGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
objGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
objGraphics.TextContrast = 0;
Here is final image with these settings on white background:
Exactly the same, thanks for suggestions and replies.
I'm not sure it will help but why not create your font without the function call, like this:
Font textFont = new Font(textFontFamily, textSize, GraphicsUnit.Pixel);
I built something to generate image buttons using similar functionality and I had issues with kerneling and the font not stretching to the desired with. The following settings got me really close to what I wanted but still not 100%.
objGraphics2.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
objGraphics2.TextRenderingHint = System.Drawing.Drawing2D.TextRenderingHint.AntiAliasGridFit;
Set Graphics.TextRenderingHint to SingleBitPerPixelGridFit.
I'm not sure if this will solve the issue, but I had a similar problem with drawing text in Direct3D, check out PixelOffsetMode, set it to Half.