C# Use Magick.NET for image format conversion

C# uses Magick.NETto convert the image format, modify the size ( .ico .jpg .png .gif .bmp), and solve the problem of pngturning jpgtransparent to black

I read many other blog format conversion codes, and after trying it, I found that many pictures converted to ico can be viewed normally, but they cannot be used at all. The simplest ones can't even be used as Wiformsoftware icons. Finally, I pyfound this by referring to the code py. PythonMagickThe package is very easy to use. After careful inspection, I found that C#there are similar packages. There is Magick.NETnot much nonsense, let's go directly to the topic!

1. Installation NuGetpackage

Insert picture description here

2. Core code

Tried several formats, gif/jpg/png/icocan be system conversion, bmpcan be converted into the other, turn the other bmpwill complain, bmpdo not care, and this year with basically no one bmp, just as Microsoft's ie, people cry!

new Thread(() => {
    
    
    try {
    
    
        button1.Enabled = false;
        using (MagickImage image = new MagickImage(filePath)) {
    
    
            //格式
            string file_format = file_format_comboBox.SelectedItem.ToString().Trim();
            if (file_format.EndsWith("ico")) {
    
    
                file_format = ".ico";
            } else if (file_format.EndsWith("png")) {
    
    
                file_format = ".png";
            } else if (file_format.EndsWith("jpg")) {
    
    
                file_format = ".jpg";
                //质量百分比
                string quality = quality_trackBar.Value.ToString();
                //原图质量的百分比进行压缩
                image.Quality = Convert.ToInt32(quality);
                //将透明色更改成白色(这里不指定默认是黑色)
                image.Opaque(Color.Transparent, Color.White);
            }
 
            string width_text = width_textBox.Text.Trim();
            string height_text = height_textBox.Text.Trim();
 
            if (!defaultSize_checkBox.Checked) {
    
    
                if (!Regex.IsMatch(width_text, "^[1-9]\\d*$")) {
    
    
                    MessageBox.Show("宽度错误");
                    return;
                }
                if (!Regex.IsMatch(height_text, "^[1-9]\\d*$")) {
    
    
                    MessageBox.Show("高度错误");
                    return;
                }
                int new_width = Convert.ToInt32(width_text);
                int new_height = Convert.ToInt32(height_text);
 
                if (file_format.EndsWith("ico")) {
    
    
                    if (new_width > 256 || new_height > 256) {
    
    
                        MessageBox.Show("ico格式宽高不可超过256", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
 
                if (new_width <= img_width && new_height <= img_height) {
    
    
                    //缩小:设定的宽高都比原图小
                    int max = new_width > new_height ? new_width : new_height;
                    image.Resize(max, max);
                } else {
    
    
                    //等比例放大
                    decimal d1 = Convert.ToDecimal(new_width) / Convert.ToDecimal(img_width);
                    decimal d2 = Convert.ToDecimal(new_height) / Convert.ToDecimal(img_height);
                    decimal maxMult = d1 > d2 ? d1 : d2;
                    int max_X = Convert.ToInt32(maxMult * Convert.ToDecimal(img_width));
                    int max_Y = Convert.ToInt32(maxMult * Convert.ToDecimal(img_height));
                    image.Resize(max_X, max_Y);
                }
                double[] ProjectTransform =
                {
    
    
                     0,0,0,0,  //左上角      
                     image.Width,0,new_width,0,    //右上角
                     0,image.Height,0,new_height,   //左下角
                     image.Width,image.Height,new_width,new_height//右下角
                };
 
                //按照ProjectTransform的坐标点进行拉伸或缩放
                image.Distort(DistortMethod.Perspective, ProjectTransform);
                //因为按大小进行拉伸或缩放后,其他区域会糊掉,所以要裁剪出我们的所需的大小,既缩放拉伸或的清楚区域
                image.Crop(new_width, new_height);
            } else {
    
    
                image.Resize(Convert.ToInt32(width_text), Convert.ToInt32(height_text));
            }
 
            string newFileName = @"C:\Users\Administrator\Desktop\new_" + Path.GetFileNameWithoutExtension(filePath) + file_format;
            try {
    
    
                image.Write(newFileName);
            } catch (Exception ee) {
    
    
                if (ee.Message.Contains("width or height exceeds limit")) {
    
    
                    MessageBox.Show("宽度或高度超过限制", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                } else {
    
    
                    MessageBox.Show(ee.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
 
            newFile_label.Text = newFileName;
        }
    } catch (Exception ee) {
    
    
        Console.WriteLine(ee);
    } finally {
    
    
        button1.Enabled = true;
    }
}).Start();

The code to solve the problem of pngturning the jpgtransparent background into black:

//将透明色替换成白色(这里不指定默认是黑色)
image.Opaque(Color.Transparent, Color.White);

One more thing to note is that when modifying the size, if the width or height is MagickImagelarger than the original picture size, then you need to zoom in ( Resize) proportionally , then stretch ( Distort), and finally crop it.

Guess you like

Origin blog.csdn.net/WuLex/article/details/107931435