[工具]图片等比例压缩工具

摘要:
在线磁盘中有这样一个功能,您需要获取所有图片的列表。经过思考,我认为最好在布局中生成相同比例的图片。所以使用压缩工具是可以的。

写在前面

在网盘中有这样一个功能,需要获取所有图片的列表,想来想去,觉得还是生成相同比例的图片,在排版上更美观一些。所以就没事高了一个压缩的工具玩玩。

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Wolfy.ImageCompress
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private string _strImageFilter = "All Image Files|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff|" +
                "Windows Bitmap(*.bmp)|*.bmp|" +
                "Windows Icon(*.ico)|*.ico|" +
                "Graphics Interchange Format (*.gif)|(*.gif)|" +
                "JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg|" +
                "Portable Network Graphics (*.png)|*.png|" +
                "Tag Image File Format (*.tif)|*.tif;*.tiff";
        private string[] filePaths = null;
        private void btnOpenImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = _strImageFilter;
            ofd.Multiselect = true;
            if (ofd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                filePaths = ofd.FileNames;
            }
            if (filePaths != null)
            {
                this.plBefore.BackgroundImage = Image.FromFile(filePaths[0]);
            }
        }

        /// <summary>
        /// 等比例压缩图片
        /// </summary>
        private async Task<string> SaveImageByWidthHeight(int intImgCompressWidth, int intImgCompressHeight, Stream stream, string strFileSavePath)
        {
            return await Task.Run<string>(() =>
            {
                //从输入流中获取上传的image对象
                using (Image img = Image.FromStream(stream))
                {
                    //根据压缩比例求出图片的宽度
                    int intWidth = intImgCompressWidth / intImgCompressHeight * img.Height;
                    int intHeight = img.Width * intImgCompressHeight / intImgCompressWidth;
                    //画布
                    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, new Size(intImgCompressWidth, intImgCompressHeight)))
                    {
                        //在画布上创建画笔对象
                        using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //将图片使用压缩后的宽高,从0,0位置画在画布上
                            graphics.DrawImage(img, 0, 0, intImgCompressWidth, intImgCompressHeight);
                            //保存图片
                            bitmap.Save(strFileSavePath);
                        }
                    }
                }
                return strFileSavePath;
            });

        }
        /// <summary>
        /// 界面压缩比例信息提示
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        private string SetCompressMsg(int width, int height)
        {
            this.txtWidth.Text = width.ToString();
            this.txtHeight.Text = height.ToString();
            this.plImageCompress.Width = width;
            this.plImageCompress.Height = height;
            this.lblImageAfter.Text = width.ToString() + "X" + height.ToString();
            return this.lblImageAfter.Text;
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            SetCompressMsg(80, 80);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                this.txtSavePath.Text = fbd.SelectedPath;
            }

        }

        private async void btnRun_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtHeight.Text) || string.IsNullOrEmpty(this.txtWidth.Text))
            {
                MessageBox.Show("请填写压缩后的图片的宽高");
                return;
            }
            if (string.IsNullOrEmpty(this.txtSavePath.Text))
            {
                MessageBox.Show("请选择文件保存路径");
                return;
            }
            int width = Convert.ToInt32(this.txtWidth.Text);
            int height = Convert.ToInt32(this.txtHeight.Text);
            if (width <= 0 || height <= 0)
            {
                MessageBox.Show("宽高数据不合法,请重新填写");
                return;
            }
            string saveformat = SetCompressMsg(width, height);
            if (filePaths != null)
            {
                foreach (var path in filePaths)
                {
                    string fileName = Path.GetFileNameWithoutExtension(path);
                    string fileExt = Path.GetExtension(path);
                    this.plBefore.BackgroundImage = Image.FromFile(path);
                    string fileNewName = fileName + "_" + saveformat + fileExt;
                    string fileSavePath = Path.Combine(this.txtSavePath.Text, fileNewName);
                    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        await SaveImageByWidthHeight(width, height, fs, fileSavePath);
                        this.plImageCompress.BackgroundImage = Image.FromFile(fileSavePath);
                    }

                }
            }
            else
            {
                MessageBox.Show("请选择图片");
            }
        }


    }
}

界面

[工具]图片等比例压缩工具第1张

支持图片多选

压缩后

[工具]图片等比例压缩工具第2张

[工具]图片等比例压缩工具第3张

总结

工具实现起来很简单,通过异步的方式进行压缩,速度还是比较快的。

免责声明:文章转载自《[工具]图片等比例压缩工具》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇ExtJS学习之路第七步:contentEl与renderTo的区别chinaMap下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Databricks 第5篇:Databricks文件系统(DBFS)

Databricks 文件系统 (DBFS,Databricks File System) 是一个装载到 Azure Databricks 工作区的分布式文件系统,可以在 Azure Databricks 群集上使用。 一个存储对象是一个具有特定格式的文件,不同的格式具有不同的读取和写入的机制。 DBFS 是基于可缩放对象存储的抽象,可以根据用户的需要动态...

dateutil

Date、long、Calendar之间的相互转换 //当前时间 Date date = DateUtil.date(); //当前时间 Date date2 = DateUtil.date(Calendar.getInstance()); //当前时间 Date date3 = DateUtil.date(System.currentTimeMillis...

jmeter之BeanShell Sampler实现当前时间加1写法和指定日期

首先获取当前时间: import java.util.*;import java.text.SimpleDateFormat;String str1 = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());String str2 = (new SimpleDateFormat("hh:mm:ss...

[Android]Android四大组件之ContentProvider

URI简介 URI(Universal Resource Identifier),又被称为"通用资源标志符"。 URI由许多部分所组成,示例及解说如下: Content URIs介绍 Android遵循URI的标准,定义了一套专用的Uri(即,Content URIs)。并且,Android提供了ContentUris、UriMatcher等类用于操作...

C#学习笔记(22)——C#创建文本文件txt并追加写入数据

ref: https://www.cnblogs.com/Jacklovely/p/7263844.html 说明(2017-7-31 16:25:06): 1. 有两种办法,第一种是用FileStream创建txt,用StreamWriter写入数据,期间还要加上判断,是否存在这个txt文件,如果不存在就创建,存在就追加写入。太麻烦了! 2. 第二种是直...

更改火狐主页与服务器网络检测

主程序: 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows.Forms; 6 using System.IO; 7 using System.Di...