C#图片按比例缩放的实现代码

代码如下:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace Publics
{
    public class ImgHelper
    {
        public static void AdjustPhoto(int toWidth, int toHeight, string filePath, string fromFileName, string toFileName, int maxWidth, int maxHeight)
        {
            Image originalImage = Image.FromFile(filePath + "/" + fromFileName);
            //如果尺寸不够返回保存原图
            if (originalImage.Width < toWidth && originalImage.Height < toHeight)
            {
                originalImage.Save(filePath + "/" + toFileName);
                originalImage.Dispose();
                return;
            }

//根据图片大小获取新图片从原图片截取的区域
            int x, y, w, h;
            if (toHeight > 0)
            {
                if (toWidth > 0)
                {
                    if (originalImage.Width > toWidth && originalImage.Height > toHeight)
                    {
                        w = toWidth;
                        h = toWidth * originalImage.Height / originalImage.Width;

if (h > toHeight)
                        {
                            h = toHeight;
                            w = toHeight * originalImage.Width / originalImage.Height;
                            x = (toWidth - w) / 2;
                            y = 0;
                        }
                        else
                        {
                            x = 0;
                            y = (toHeight - h) / 2;
                        }
                    }
                    else if (originalImage.Width > toWidth)
                    {
                        w = toWidth;
                        h = toWidth * originalImage.Height / originalImage.Width;
                        x = 0;
                        y = (toHeight - h) / 2;
                    }
                    else if (originalImage.Height > toHeight)
                    {
                        h = toHeight;
                        w = toHeight * originalImage.Width / originalImage.Height;
                        x = (toWidth - w) / 2;
                        y = 0;
                    }
                    else
                    {
                        w = originalImage.Width;
                        h = originalImage.Height;
                        x = (toWidth - w) / 2;
                        y = (toHeight - h) / 2;
                    }
                }
                else
                {
                    if (originalImage.Height > maxHeight)
                    {
                        toWidth = toHeight * originalImage.Width / originalImage.Height;
                        x = 0;
                        y = 0;
                        w = toWidth;
                        h = toHeight;

}
                    else
                    {
                        x = 0;
                        y = 0;
                        w = originalImage.Width;
                        h = originalImage.Height;
                        toWidth = originalImage.Width;
                        toHeight = originalImage.Height;
                    }
                }
            }
            else
            {
                if (originalImage.Width > maxWidth)
                {
                    toHeight = toWidth * originalImage.Height / originalImage.Width;
                    x = 0;
                    y = 0;
                    w = toWidth;
                    h = toHeight;

}
                else
                {
                    x = 0;
                    y = 0;
                    w = originalImage.Width;
                    h = originalImage.Height;
                    toWidth = originalImage.Width;
                    toHeight = originalImage.Height;
                }
            }
            Bitmap bm = new Bitmap(toWidth, toHeight);
            Graphics g = Graphics.FromImage(bm);

g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.Clear(Color.White);
            g.DrawImage(originalImage, new Rectangle(x, y, w, h), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);

long[] quality = new long[1];
            quality[0] = 80;

EncoderParameters encoderParams = new EncoderParameters();
            EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo jpegICI = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];//设置JPEG编码
                    break;
                }
            }
            if (jpegICI != null)
            {

//bm.Save(Server.MapPath(path + "/thumb_" + filename), jpegICI, encoderParams);
                bm.Save(filePath + "/" + toFileName, jpegICI, encoderParams);
            }

bm.Dispose();
            originalImage.Dispose();
            g.Dispose();
        }

/// <summary>
        /// 保持比例图像缩放简易算法
        /// </summary>
        /// <param name="spcWidth"></param>
        /// <param name="spcHeight"></param>
        /// <param name="orgWidth"></param>
        /// <param name="orgHeight"></param>
        /// <returns></returns>
        public static Dictionary<string, int> AdjustSize(int spcWidth, int spcHeight, int orgWidth, int orgHeight)
        {
            Dictionary<string, int> size = new Dictionary<string, int>();
            // 原始宽高在指定宽高范围内,不作任何处理 
            if (orgWidth <= spcWidth && orgHeight <= spcHeight)
            {
                size["Width"] = orgWidth;
                size["Height"] = orgHeight;
            }
            else
            {
                // 取得比例系数 
                float w = orgWidth / (float)spcWidth;
                float h = orgHeight / (float)spcHeight;
                // 宽度比大于高度比 
                if (w > h)
                {
                    size["Width"] = spcWidth;
                    size["Height"] = (int)(w >= 1 ? Math.Round(orgHeight / w) : Math.Round(orgHeight * w));
                }
                // 宽度比小于高度比 
                else if (w < h)
                {
                    size["Height"] = spcHeight;
                    size["Width"] = (int)(h >= 1 ? Math.Round(orgWidth / h) : Math.Round(orgWidth * h));
                }
                // 宽度比等于高度比 
                else
                {
                    size["Width"] = spcWidth;
                    size["Height"] = spcHeight;
                }
            }
            return size;
        }
    }
}

(0)

相关推荐

  • Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果(附demo源码下载)

    本文实例讲述了Asp.net(C#)读取数据库并生成JS文件制作首页图片切换效果的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.IO; public partial

  • asp.net(C#)使用QRCode生成图片中心加Logo或图像的二维码实例

    本文实例讲述了asp.net(C#)使用QRCode生成图片中心加Logo或图像的二维码.分享给大家供大家参考,具体如下: <%@ WebHandler Language="C#" Class="GetQRCode" %> using System; using System.Web; using ThoughtWorks.QRCode.Codec; using ThoughtWorks.QRCode.Codec.Data; using ThoughtW

  • C# 将字节流转换为图片的实例方法

    复制代码 代码如下: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Drawing; usingSystem.IO; namespaceMicrosoft.Form.Base {     classImageToByte     {         /// <summary>         /// 图片转换成字节流         /// </s

  • asp.net(c#)获取内容第一张图片地址的函数

    首先找到内容里面第一个<img标签的位置,然后找到从这个起的第一个>的位置,得到第一张图片的完整标签. 然后通过分隔空格得到图片的各个属性和属性值,提取src的值就是图片的地址 代码如下: 复制代码 代码如下: /// <summary> /// 获取文中图片地址 /// </summary> /// <param name="content">内容</param> /// <returns>地址字符串</r

  • ASP.NET(C#)实现一次性动态上传多张图片的代码(多个文件)

    在做asp.net的Web开发的时候,我们经常会遇到一次性上传多个文件的需求.通常我们的解决方法是固定放多个上传文件框,这样的解决办法显然是不合理的,因为一次上传多个,就意味着数量不确定.因此我们就要让这些文件上传框动态添加,下面我以我做的一个图库管理中的上传图片的功能为例 先看效果: 打开的初始界面: 默认是上传一个图片,但当我们点"增加图片"按钮时可以实现选择多个图片及其描述同时上传,本功能限制一次最多只能上传8张,且每张图片大小不超过1M,这个大家可根据实际情况更改! 如图: 下

  • c#实现图片二值化例子(黑白效果)

    C#将图片2值化示例代码,原图及二值化后的图片如下: 原图: 二值化后的图像: 实现代码: using System; using System.Drawing; namespace BMP2Grey { class Program { static void ToGrey(Bitmap img1) { for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor

  • asp.net(c#)判断远程图片是否存在

    复制代码 代码如下: private int GetUrlError(string curl) { int num = 200; if(this.method==1) { HttpWebRequest request=(HttpWebRequest) WebRequest.Create(new Uri(curl)); ServicePointManager.Expect100Continue=false; try { ((HttpWebResponse)request.GetResponse()

  • asp.net(c#)实现从sqlserver存取二进制图片的代码

    下面说说主要实现思路: 1.存取图片 (1).将图片文件转换为二进制并直接存进sql server 复制代码 代码如下: //UploadHelper.cs /// <summary> /// 将图片转化为长二进制 /// </summary> /// <param name="photopath"></param> /// <returns></returns> public static Byte[] SetI

  • asp.net(c#)编程实现将彩色图片变灰阶图片的方法示例

    本文实例讲述了asp.net(c#)编程实现将彩色图片变灰阶图片的方法.分享给大家供大家参考,具体如下: 代码如下: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI

  • c#图片缩放图片剪切功能实现(等比缩放)

    所谓c#图片处理高级应,多数是基于.net framework类库完成 复制代码 代码如下: using system;using system.collections.generic;using system.text;using system.io;using system.drawing;using system.drawing.drawing2d;using system.drawing.imaging; namespace wujian.common{    /// <summary>

  • asp.net(C#)压缩图片,可以指定图片模板高宽

    复制代码 代码如下: //生成缩略图函数 //顺序参数:源图文件流.缩略图存放地址.模版宽.模版高 //注:缩略图大小控制在模版区域内 public static void MakeSmallImg(System.IO.Stream fromFileStream, string fileSaveUrl, System.Double templateWidth, System.Double templateHeight) { //从文件取得图片对象,并使用流中嵌入的颜色管理信息 System.Dr

  • C#识别出图片里的数字和字母

    一个图片识别小工具,原先主要是识别以前公司的软件注册码截图里的数字和字母(每次要一个一个框复制出来粘贴到注册器里,很麻烦!),因为注册码出现的字母和数字基本就那几个,所以识别库的范围设定的比较少. 原理和算法在代码中做了详细说明,功能存在很大的局限性,但我的想法是把这个思路和实现的办法共享出来. 源码下载地址: http://git.oschina.net/bobo2cj/iamge2text /* * 开发思路:图片灰度处理,二进制,然后和图片中的字二进制库精确对比 * * 获取字库:通过下面

随机推荐