且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用程序化文本缩小打印质量图像的文件大小,而不会降低打印质量

更新时间:2021-08-04 23:10:50

Hi Pingpong689,

Hi Pingpong689,

当然你可以通过以下完整演示来缩小图片:

Sure you can reduce the picture with the following complete demo:

        public static string imageFilePath = @"C:\Users\v-baf\Desktop\Picon\8.jpg";
        public static string imageBaseFilePath = @"D:\New folder (9)\";

        private void button1_Click(object sender, EventArgs e)
        {
            A4SizeDpi600();

            Image img = Image.FromFile(imageBaseFilePath + "CertDpi600.png");
            SaveJpeg(imageBaseFilePath + "Result.png", img, 50);
        }

        private static void A4SizeDpi600()
        {
            const int dotsPerInch = 600; // define the quality in DPI
            const double widthInInch = 10; // width of the bitmap in INCH
            const double heightInInch = 8; // height of the bitmap in INCH
            using (Bitmap bitmap = new Bitmap(Image.FromFile(imageFilePath), (int)(widthInInch * dotsPerInch), (int)(heightInInch * dotsPerInch))) //10*600=6000, 8*600=4800
            {
                bitmap.SetResolution(dotsPerInch, dotsPerInch);

                using (Graphics graphics = Graphics.FromImage(bitmap))
                {

                    graphics.DrawString("Some text here", new Font("Times New Roman", 0.3f, FontStyle.Regular, GraphicsUnit.Inch), Brushes.Black, 1400f, 2100f);
                    //more text here
                    // Save the bitmap

                    bitmap.Save(imageBaseFilePath + "CertDpi600.png");//file type can be any 
                }
            }
        }

        public static void SaveJpeg(string path, Image img, int quality)
        {
            if (quality < 0 || quality > 100)
                throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

            // Encoder parameter for image quality 
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            // JPEG image codec 
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];

            return null;
        }

结果截图:

请参阅
缩小图像大小C#[关闭]。

希望这会有所帮助!

最诚挚的问候,

Stanly