C# 生成缩略图 去除图片旋转角度

图片生成缩略图会有旋转角度

/// <summary>
/// 测试JRE图片压缩后图片会旋转问题
/// </summary>
public void Uploadimg1()
{
    HttpPostedFile hpf = HttpContext.Current.Request.Files[0];
    var context = HttpContext.Current;
    string newurl = context.Server.MapPath("/upload/img/" + DateTime.Now.ToString("yyyyMM") + "/");
    string newfilename = hpf.FileName;
    hpf.SaveAs(newurl + "_" + newfilename);
    hpf.SaveAs(newurl + newfilename);
    JREUpLoadImage(hpf, newurl, "sm_", 244, 165, newfilename);
    File.Delete(newurl + "_" + newfilename);
}

/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="upImage"></param>
/// <param name="sSavePath"></param>
/// <param name="sThumbExtension"></param>
/// <param name="intThumbWidth"></param>
/// <param name="intThumbHeight"></param>
/// <param name="filename"></param>
private void JREUpLoadImage(HttpPostedFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight, string filename)
{
    string sThumbFile = "";
    string sFilename = filename;
    int nFileLen = upImage.ContentLength;
    string extendName = System.IO.Path.GetExtension(upImage.FileName).ToLower();

    byte[] myData = new Byte[nFileLen];
    upImage.InputStream.Read(myData, 0, nFileLen);
    sFilename = System.IO.Path.GetFileName(filename);
    int file_append = 0;

    //以上为上传原图
    try
    {
        //原图加载
        using (Image sourceImage = Image.FromFile(sSavePath + sFilename))
        {

            //旋转图片
            RotateImage(sourceImage);

            //原图宽度和高度
            int width = sourceImage.Width;
            int height = sourceImage.Height;
            int smallWidth;
            int smallHeight;
            //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)
            if ((decimal)width / intThumbWidth <= ((decimal)height) / intThumbHeight)
            {
                smallWidth = width * intThumbHeight / height;
                smallHeight = intThumbHeight;
            }
            else
            {
                smallWidth = intThumbWidth;
                smallHeight = height * intThumbWidth / width;
            }
            //判断缩略图在当前文件夹下是否同名称文件存在
            file_append = 0;
            sThumbFile = sThumbExtension + sFilename;
            while (System.IO.File.Exists(sSavePath + sThumbFile))
            {
                file_append++;
                sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(upImage.FileName) + file_append.ToString() + ".jpg";
            }

            //缩略图保存的绝对路径
            string smallImagePath = sSavePath + sThumbFile;
            //新建一个图板,以最小等比例压缩大小绘制原图
            using (Image bitmap = new Bitmap(smallWidth, smallHeight))
            {
                //绘制中间图
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                {
                    //高清,平滑
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.Clear(Color.Black);
                    g.DrawImage(
                    sourceImage,
                    new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                    new System.Drawing.Rectangle(0, 0, width, height),
                    System.Drawing.GraphicsUnit.Pixel
                    );
                }
                //新建一个图板,以缩略图大小绘制中间图
                using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                {
                    //绘制缩略图
                    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                    {
                        //高清,平滑
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.Clear(Color.Black);
                        int lwidth = (smallWidth - intThumbWidth) / 2;
                        int bheight = (smallHeight - intThumbHeight) / 2;
                        g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                        g.Dispose();
                        bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
            }
        }
    }
    catch
    {
        //出错则删除
        System.IO.File.Delete(sSavePath + sFilename);
    }
}
/// <summary>
/// 旋转图片
/// </summary>
/// <param name="img"></param>
private void RotateImage(Image img) {
    var exif = ReadExif(img);
    if (exif.ContainsKey("Orientation"))
    {
        switch (int.Parse(exif["Orientation"]))
        {
            case 2:
                img.RotateFlip(RotateFlipType.RotateNoneFlipX);//horizontal flip
                break;
            case 3:
                img.RotateFlip(RotateFlipType.Rotate180FlipNone);//right-top
                                                                 //img = Rotate((Bitmap)img, 180);
                break;
            case 4:
                img.RotateFlip(RotateFlipType.RotateNoneFlipY);//vertical flip
                break;
            case 5:
                img.RotateFlip(RotateFlipType.Rotate90FlipX);
                break;
            case 6:
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);//right-top
                break;
            case 7:
                img.RotateFlip(RotateFlipType.Rotate270FlipX);
                break;
            case 8:
                img.RotateFlip(RotateFlipType.Rotate270FlipNone);//left-bottom
                break;
        }
    }
}

/// <summary>
/// 获取图片旋转角度
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
private Dictionary<string, string> ReadExif(Image image)
{
    var exif = new Dictionary<string, string>();
    var properties = image.PropertyItems;
    foreach (var property in properties)
    {
        switch (property.Id)
        {
            case 0x010E:
                exif["ImageTitle"] = ASCIIToString(property.Value);
                break;
            case 0x010F:
                exif["Make"] = ASCIIToString(property.Value);
                break;
            case 0x0110:
                exif["Model"] = ASCIIToString(property.Value);
                break;
            case 0x0112:
                exif["Orientation"] = ShortToString(property.Value, 0);
                break;
            case 0x011A:
                exif["XResolution"] = RationalToSingle(property.Value, 0);
                break;
            case 0x011B:
                exif["YResolution"] = RationalToSingle(property.Value, 0);
                break;
            case 0x0128:
                exif["ResolutionUnit"] = ShortToString(property.Value, 0);
                break;
            case 0x0131:
                exif["Software"] = ASCIIToString(property.Value);
                break;
            case 0x0132:
                exif["DateTime"] = ASCIIToString(property.Value);
                break;
            //GPS
            case 0x0002:
                exif["GPSLatitude"] = string.Format("{0}°{1}′{2}″",
                                                    RationalToSingle(property.Value, 0),
                                                    RationalToSingle(property.Value, 8),
                                                    RationalToSingle(property.Value, 16)
                                                    );
                break;
            case 0x0004:
                exif["GPSLongitude"] = string.Format("{0}°{1}′{2}″",
                                                    RationalToSingle(property.Value, 0),
                                                    RationalToSingle(property.Value, 8),
                                                    RationalToSingle(property.Value, 16)
                                                    );
                break;
            case 0x0006:
                exif["GPSAltitude"] = RationalToSingle(property.Value, 0);
                break;
        }
    }
    return exif;
}

string ByteToString(byte[] b, int startindex)
{
    if (startindex + 1 <= b.Length)
        return ((char)b[startindex]).ToString();
    else
        return string.Empty;
}

string ShortToString(byte[] b, int startindex)
{
    if (startindex + 2 <= b.Length)
        return BitConverter.ToInt16(b, startindex).ToString();
    else
        return string.Empty;
}

string RationalToSingle(byte[] b, int startindex)
{
    if (startindex + 8 <= b.Length)
        return (BitConverter.ToSingle(b, startindex) / BitConverter.ToSingle(b, startindex + 4)).ToString();
    else
        return string.Empty;
}

string ASCIIToString(byte[] b)
{
    return Encoding.ASCII.GetString(b);
}

生成缩略图 去除旋转角度

原文地址:https://www.cnblogs.com/zhyue93/p/image_remote.html

时间: 2024-10-11 15:54:25

C# 生成缩略图 去除图片旋转角度的相关文章

PHP.25-TP框架商城应用实例-后台1-添加商品功能、钩子函数、在线编辑器、过滤XSS、上传图片并生成缩略图

添加商品功能 1.创建商品控制器[C] /www.test.com/shop/Admin/Controller/GoodsController.class.php <?php namespace Admin\Controller; use Think\Controller; //后台添加商品功能控制器 class GoodsController extends Controller { //显示和处理表单 public function add() { //判断用户是否提交了表单(如果提交了,就

生成缩略图的PHP上传图片类

做图片类网站的朋友可能都有自己上传图片的方式方法.这里给大家介绍一个php上传图片类,它可以验证上传文件是否为图片,图片的格式是否是网站所接受的:还可以生成指定大小的缩略图.具体方法如下所示: <?phpclass UploadComponent { var $imageData = array(); var $destinationDir = NULL; var $thumbDestinationDir = NULL; var $imageSize = array(500,500); var

[原创]超强C#图片上传,加水印,自动生成缩略图源代码

<%@ Page Language=“C#“ AutoEventWireup=“true“ %> <%@ Import Namespace=“System“ %> <%@ Import Namespace=“System.IO“ %> <%@ Import Namespace=“System.Net“ %> <%@ Import NameSpace=“System.Web“ %> <%@ Import NameSpace=“Legalsof

根据图片URL裁切并生成缩略图

package jtest; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.CropImageFilter; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import

thinkphp 3.2.2 图片上传gif类型生成缩略图错误

对gif图片处理不怎么了解, thinkphp3.2.2 对gif图片处理有点小bug,不才,解决不了 但是让其正常的生产缩略图,找到对应的driver类,将gif类型判断的代码注释掉,可以正常生成缩略图, 先简单的解决下, 具体的解决,需要自己找类或者写了.目前不想研究,以后再看.

图片生成缩略图

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Drawing; using System.IO; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace Common { /// <summary>    

js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能

html: <form action="<{:AppLink('circle/uploadimg')}>" id="imageform" method="post" enctype="multipart/form-data">     <input name="photoimg" type="file" id="xwzx_f" style

图片处理类,实现图片处理,包括添加水印和生成缩略图

<?php /** *=================================================================== * image.class.php 图片处理类,实现图片处理,包括添加水印和生成缩略图 * @author 王超平 * @copyright 传智播客PHP学院 2006-2013 * @version 1.0 * 2013年3月25日22:10:38 *===========================================

C#上传图片同时生成缩略图,控制图片上传大小。

1 #region 上传图片生成缩略图 2 /// <summary> 3 /// 上传图片 4 /// </summary> 5 /// <param name="sender"></param> 6 /// <param name="e"></param> 7 public void btnUpload_Click(object sender, EventArgs e) 8 { 9 //检查