This question may sound familiar but i have searched internet and couldn't find a solution to it.
I know for printing we can use Crystal Report but i am discarding that idea because of it's certain disadvantages. Here are some of the disadvantages:-
Needs installation on PC and if the Visual Studio version is 2017 then you have to download 200MB+ setup.
If you have made certain objects like textobject and lines in one section and you have to add something in the middle of it then you have to manually set location of every object otherwise if you collectively select all the object and move it then their original location and the spacing between each object gets lost.
Currently i am using VS2008 and it has crystal report integrated in it which has a well know problem of sometime changing the text of every textobject and adding an "i" in it for some reason.
I also tried to download an alternate to crystal report. But its interface is not that friendly.
Alternate that i am choosing
Now i have designed my report on Windows Form. When i am trying to print, its quality is worse as compared to Crystal Reports print. Here is the code for it
private System.IO.Stream streamToPrint;
string streamType;
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
int x = e.MarginBounds.X;
int y = e.MarginBounds.Y;
int width = image.Width;
int height = image.Height;
if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
{
width = e.MarginBounds.Width;
height = image.Height * e.MarginBounds.Width / image.Width;
}
else
{
height = e.MarginBounds.Height;
width = image.Width * e.MarginBounds.Height / image.Height;
}
System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
}
private void btnPrint_Click(object sender, EventArgs e)
{
string fileName = Application.StartupPath + "\\PrintPage.jpg";
using (Graphics gfx = this.CreateGraphics())
{
using (Bitmap bmp = new Bitmap(this.Width, this.Height, gfx))
{
this.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
bmp.Save(fileName);
}
}
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
}
public void StartPrint(Stream streamToPrint, string streamType)
{
this.printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
this.streamToPrint = streamToPrint;
this.streamType = streamType;
System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.AllowSomePages = true;
PrintDialog1.ShowHelp = true;
PrintDialog1.Document = printDoc;
DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDoc.Print();
//docToPrint.Print();
}
}
private void Frm_Test_Shown(object sender, EventArgs e)
{
try
{
btnPrint_Click(sender, e);
}
catch (Exception ex) { clsUtility.ShowErrMsg(ex.Message); }
}
I understand the reason why it is doing so because of the image and screen resolution thing (Ref : https://stackoverflow.com/a/12547806/2994869). The workaround people mentioned was to increase the size of windows form and it's object by 6 times but that had the same result still the quality is worse.
Is there any workaround or any trick that i can do to print a windows form so that quality is near to that of Crystal Report's.
For high quality you need to create a source with higher resolution than the screen, which is all you can get from DrawToBitmap.
Using DrawToBitmap will only help if you can enlarge a single control a lot. For the whole form it will not help.
You will need to fully re-create the parts you want to print and use as many DrawString and other DrawXXX methods as needed. Yes, a lot of work. (But fun ;-)
But the code you show also blunders by using a jpg file format, which was created for soft images (i.e. photographs). Change that to png and compare!
Related
I have followed a bunch of tutorials and made a screen recorder. It works by taking a screenshot and then using the AForge.video addon to convert this to avi format. The programme worked fine, but it ran out of memory after about 20 seconds. This would either crash the program or clear itself with a huge lag spike. To stop this I added a disposal method at the end of every screenshot to clear the memory. This kept the memory usage down however it makes the application hugely unstable. When I move the main window or wait for about 3 minutes on recording, the programme crashes and shows this:
A screenshot of the error
Every time I remove the dispose methods, the programme moves fine but runs out of memory quickly. Maybe I'm just using the dispose method wrong.
Here's the code that crashes the programme. There is way to much code to include it all.
counter = 0;
imagelist = new Bitmap[100000];
Globals.imgcount = 0;
Graphics g;
basePath = sel.ToString();
basePath = #"C:\Users\sim\Videos\Captures";
using (var videowriter = new VideoFileWriter())
{
videowriter.Open(basePath + "timelapse.avi", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, 9, VideoCodec.MPEG4, 1200000);
while (Globals.recording == true)
{
try
{
try
{
//takes the screenshot
bm = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
//turns it into graphics
g = Graphics.FromImage(bm);
g.CopyFromScreen(0, 0, 0, 0, bm.Size);
counter++;
videowriter.WriteVideoFrame(bm);
//display image
Bitmap original = bm;
Bitmap resized2 = new Bitmap(original, new Size(pictureBox1.Width, pictureBox1.Height));
bm = resized2;
pictureBox1.Image = bm;
Thread.Sleep(10);
if (/*counter % 18 == 0*/ true)
{
try
{
g.Dispose();
bm.Dispose();
original.Dispose();
resized2.Dispose();
}
catch
{
MessageBox.Show("Disposal error");
}
}
}
catch { }
}
catch { }
}
videowriter.Close();
}
I hope that this is enough information to figure something out.
Thanks to anyone who can help.
You are doing many things unnecessary eg creating 3 bitmaps instead of one, setting the image bm to picbox and of cource running the code to main UI. Of cource it will freeze. For an easy and quick fix create a timer. Set the interval to 10. Create a button that will stop the timer and one that will start it and record. In timer instead of calling
repeatedly
pictureBox1.Image = bm;
use
pictureBox1.Invalidate();
Code:
//not good names. change it to something meaningfull
private Bitmap bm;
private Graphics g;
VideoFileWriter videowriter;
private void timer1_Tick( object sender, EventArgs e ) {;
//takes the screenshot
g.CopyFromScreen( 0, 0, 0, 0, bm.Size );
videowriter.WriteVideoFrame(bm);
pictureBox1.Invalidate();
}
The button that starts the recording:
private void Start_Click( object sender, EventArgs e ) {
//create both bitmap and graphics once!
bm = new Bitmap( Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height );
g = Graphics.FromImage( bm );
pictureBox1.Image = bm; //Just once!
basePath = sel.ToString();
basePath = #"C:\Users\sim\Videos\Captures";
videowriter = new VideoFileWriter();
videowriter.Open(basePath + "timelapse.avi", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, 9, VideoCodec.MPEG4, 1200000);
timer1.Enabled = true;
}
Button to stop recording:
private void Stop_Click( object sender, EventArgs e ) {
timer1.Enabled = false;
pictureBox1.Image = null;
bm.Dispose();
bm = null;
g.Dispose();
g = null;
videowriter.Close();
//I don't know if videowriter can be disposed if so dispose it too and set it to null
}
Also set picturebox SizeMode to StreachImage
I'm using WinForms. My program opens .Tiff image documents into a picturebox. The problem I'm having is printing high quality tiff images from the picturebox. I've tried and tested printing many times. When the document prints the words are not crisp/clear its a little blurry. I tested my printer also to check if there was a problem with my printer. I printed a regular text document using Microsoft word and it printed out clearly, so its an issue with my code.
Can someone provide me with the code to print in high quality .tiff images in my picturebox? Would I need to increase my DPI programmatically to increase the quality of the image?
This is my code.
private void DVPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.DrawImage(pictureBox1.Image, 25, 25, 800, 1050);
}
private void Print_button_Click(object sender, EventArgs e)
{
PrintPreviewDialog.Document = PrintDocument;
PrintPreviewDialog.ShowDialog();
}
After analyzing my code further, I think I figured out why my pictures are turning out blurry. When I open a Tiff document, I have in my form a back, and forward button for the multiple tiff pages. In the RefreshImage method, I think that’s where my images are turning blurry.
Here is my code:
private int intCurrPage = 0; // defining the current page (its some sort of a counter)
bool opened = false; // if an image was opened
//-------------------------------------Next and Back Button-------------------------------------------------
private void btn_Back_Click(object sender, EventArgs e)
{
if (opened) // the button works if the file is opened. you could go with button.enabled
{
if (intCurrPage == 0) // it stops here if you reached the bottom, the first page of the tiff
{ intCurrPage = 0; }
else
{
intCurrPage--; // if its not the first page, then go to the previous page
RefreshImage(); // refresh the image on the selected page
}
}
}
private void btn_Next_Click(object sender, EventArgs e)
{
if (opened) // the button works if the file is opened. you could go with button.enabled
{
if (intCurrPage == Convert.ToInt32(lblNumPages.Text)) // if you have reached the last page it ends here
// the "-1" should be there for normalizing the number of pages
{ intCurrPage = Convert.ToInt32(lblNumPages.Text); }
else
{
intCurrPage++;
RefreshImage();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
var bm = new Bitmap(pictureBox1.Image);
bm.SetResolution(600, 600);
Image image1 = new Bitmap(bm);
pictureBox1.Image = image1;
pictureBox1.Refresh();
}
public void RefreshImage()
{
Image myImg; // setting the selected tiff
Image myBmp; // a new occurance of Image for viewing
myImg = System.Drawing.Image.FromFile(#lblFile.Text); // setting the image from a file
int intPages = myImg.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); // getting the number of pages of this tiff
intPages--; // the first page is 0 so we must correct the number of pages to -1
lblNumPages.Text = Convert.ToString(intPages); // showing the number of pages
lblCurrPage.Text = Convert.ToString(intCurrPage); // showing the number of page on which we're on
myImg.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, intCurrPage); // going to the selected page
myBmp = new Bitmap(myImg, pictureBox1.Width, pictureBox1.Height); // setting the new page as an image
// Description on Bitmap(SOURCE, X,Y)
pictureBox1.Image = myBmp; // showing the page in the pictureBox1
}
myBmp = new Bitmap(myImg, pictureBox1.Width, pictureBox1.Height);
pictureBox1.Image = myBmp;
Look no further, you are rescaling the image to fit the picture box. That throws away lots of pixels in the source image, the picture box is a lot smaller than the image. The aspect ratio is only correct by accident btw.
Simplest way is to just not rescale it yourself and leave it up to the PictureBox control to do it. Albeit that it makes painting slow. The other way is to simply keep a reference to the original image. Just use a variable instead of the PictureBox.Image property.
Try this code which transforms the context of the PictureBox into Bitmap image and let you choose in which device the printing may occur:
private void myPrintDocument_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap myBitmap1 = new Bitmap(myPicturebox.Width, myPicturebox.Height);
myPicturebox.DrawToBitmap(myBitmap1, new Rectangle(0, 0, myPicturebox.Width, myPicturebox.Height));
e.Graphics.DrawImage(myBitmap1, 0, 0);
myBitmap1.Dispose();
}
private void btnPrintPicture_Click(object sender, EventArgs e)
{
System.Drawing.Printing.PrintDocument myPrintDocument1 = new System.Drawing.Printing.PrintDocument();
PrintDialog myPrinDialog1 = new PrintDialog();
myPrintDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(myPrintDocument2_PrintPage);
myPrinDialog1.Document = myPrintDocument1;
if (myPrinDialog1.ShowDialog() == DialogResult.OK)
{
myPrintDocument1.Print();
}
}
Here is my Code, I am trying to stitch two pictures together and as soon as I get to line 42 "Image img = Image.FromFile(file.FullName);" I get an out of memory error. What should I do?
namespace Practicing_Stiching
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdCombine_Click(object sender, EventArgs e)
{
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(#"C:\Users\Elder Zollinger\Desktop\Images");
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
CombineImages(files);
}
}
private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = #"C:\Users\Elder Zollinger\Desktop\Images";
List<int> imageHeights = new List<int>();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
imageLocation.Image = Image.FromFile(finalImage);
}
}
}
That's likely GDI playing tricks on you.
You see, when GDI encounters an unknown file, it will quite likely cause an OutOfMemoryException. Since you're not filtering the input images at all, I'd expect that you're simply grabbing a non-image file (or an image type that GDI doesn't understand).
Oh, and a bit sideways - make sure you set JPEG quality when saving JPEGs - the default is something like 75, which is rather bad for a lot of images. And please, do use using - it's very handy to ensure proper and timely clean-up :)
Get more memory!
But seriously, you don't appear to be filtering out files that are not image files. There are some hidden files in folders that you may be trying to open as an image accidentally, such as "Thumbs.db". Make sure that the file is an image with something like if (Path.GetExtension(file.FullPath) != ".png") continue;.
Also, on objects that you are calling .Dispose() on, consider wrapping them in a using() instead. For example:
using(var img = Image.FromFile(file.FullPath))
{
// ...
}
i want to print my form on the whole page but instead the picture looks like this :
http://i.stack.imgur.com/JSXh2.jpg
it looks very small that's why i need the form to be printed on the whole full page
here is my code :
private void button5_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocument1.Print();
}
private Bitmap _memoryImage;
private void CaptureScreen()
{
// put into using construct because Graphics objects do not
// get automatically disposed when leaving method scope
using (var myGraphics = CreateGraphics())
{
var s = Size;
_memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
using (var memoryGraphics = Graphics.FromImage(_memoryImage))
{
memoryGraphics.CopyFromScreen(Location.X, Location.Y, 0, 0, s);
}
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
var wScale = e.MarginBounds.Width / (float)_memoryImage.Width;
var hScale = e.MarginBounds.Height / (float)_memoryImage.Height;
// choose the smaller of the two scales
var scale = wScale < hScale ? wScale : hScale;
// apply scaling to the image
e.Graphics.ScaleTransform(scale, scale);
// print to default printer's page
e.Graphics.DrawImage(_memoryImage, 0, 0);
}
your help would be appreciated
try this to make a bitmap of your form:
Bitmap bm = new Bitmap(f1.Width, f1.Height);
this.DrawToBitmap(bm, new Rectangle(f1.Location, f1.Size));
maybe that's the problem! Report back if it works!
If you want to print it in landscape format than you have to rotate your bitmap using:
public Bitmap rotateInternalFunction(Bitmap bitmap)
{
bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
return bitmap;
}
I am trying to port my app in windows phone . i have to upload an image on server So it is in small Size For uploading i have done this thing in Widows Successfully but problem is when i failed in it .. here is my code for windows App
public void CompressImage(int i, int j)
{
bmp1.SetPixel(j, i, Color.FromArgb(bmp.GetPixel(j, i).R, bmp.GetPixel(j, i).G, bmp.GetPixel(j, i).B));
}
private void bLoadImage_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(file.FileName);
}
}
private void bCompression_Click(object sender, EventArgs e)
{
bmp = new Bitmap(pictureBox1.Image);
bmp1 = new Bitmap(bmp.Width, bmp.Height);
for (int i = 1; i < bmp.Height; i++)
for (int j = 1; j < bmp.Width; j++)
{
CompressImage(i, j);
}
pictureBox2.Image = bmp1;
bmp1.Save("Picture.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
After Searching on google i found out that windows Phone does not support Bitmap .. any idea how i can do the same thing in windows phone or any other alternative for doing this
You should use WriteablBitmap to reduce size of image. WriteablBitmap has number of methods for images in windows phone Here is more about writeablebitmapex.
Try to load your original image to WriteableBitmap object, then you can use SaveJpeg() extension method from System.Windows.Media.Imaging namespace, to save new image with reduced size. For example :
.......
WriteableBitmap wb = new WriteableBitmap(bitmapImageObject);
wb.SaveJpeg(stream, 120, 160, 0, 100);
.......
When you are taking picture you can choose the resolution with which the picture will be taken. This can be done by
PhotoCamera cam;
After camera initizalition.
Following code when image is capturing (in the method that captures the image)
IEnumerable<Size> resList = cam.AvailableResolutions;
Size res;
if (resList.Count() > 0)
{
res = resList.ElementAt<Size>(0);
cam.Resolution = res;
}
This sample chooses the first resolution
You can try this. It worked for me. It reduced my 9.70MB file into 270KB.
WriteableBitmap cameraCapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto, 1024, 1024);
using (IsolatedStorageFileStream myFileStream = myStore.CreateFile(fileName))
{
System.Windows.Media.Imaging.Extensions.SaveJpeg(cameraCapturedImage, myFileStream, cameraCapturedImage.PixelWidth, cameraCapturedImage.PixelHeight, 0, 85);
myFileStream.Close();
}
N.B: fileName is the name of file to save size reduced image.