• c#旋转图片并保存在本地


    c#旋转图片并保存在本地

    ①将图片读入bitmap中

    • path为绝对路径,例:String path = @"D:/desktop/test.jpg"
    Bitmap b = new Bitmap(path, true);
    
    • 1

    ②旋转图片

    参考:C# 图片旋转_kingwebo’sZone的博客-CSDN博客

    • angle为角度不是弧度。
    • Graphics.RotateTransform(angle),旋转方向默认是顺时针旋转。
    public static Bitmap rotateImage(Bitmap b, float angle)
    {
        //创建位图用于旋转图片
        Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
        //初始化Graphics类
        Graphics g = Graphics.FromImage(returnBitmap);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        //移动坐标原点到图片中心
        g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
        //顺时针旋转对应angle的角度
        g.RotateTransform(angle);
        //移动坐标原地啊为原来的位置
        g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
        //构造图片
        g.DrawImage(b, new System.Drawing.Point(0, 0));
        //返回位图
        return returnBitmap;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    ③完整代码测试

     public static Bitmap rotateImage(Bitmap b, float angle)
     {
         //创建位图用于旋转图片
         Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
         //初始化Graphics类
         Graphics g = Graphics.FromImage(returnBitmap);
         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
         //移动坐标原点到图片中心
         g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
         //顺时针旋转对应angle的角度
         g.RotateTransform(angle);
         //移动坐标原地啊为原来的位置
         g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
         //构造图片
         g.DrawImage(b, new System.Drawing.Point(0, 0));
         //返回位图
         return returnBitmap;
     }
    
    
    // ocr c#入口方法
    public static void Main(string[] args)
    {
        Console.WriteLine(1);
        Bitmap b = new Bitmap(@"D:/desktop/git-space/local_baidu_ocr2/local_baidu_ocr/local_baidu_ocr/bin/images/4.jpg", true);
        Bitmap ans = rotateImage(b, 90);
        ans.Save("../images/6.jpg", System.Drawing.Imaging.ImageFormat.Png);
        Console.ReadLine();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    ④程序结果

    • 其中4.jpg为原图,6.jpg为旋转后的结果。顺时针旋转了90°。
      在这里插入图片描述

    ⑤缺陷

    • 如果按照非90的倍数的角度去旋转,旋转后的结果图片会留有空白。(改进方案:考虑旋转后对图片中的目标进行提取)
      在这里插入图片描述
  • 相关阅读:
    【Java】医院智能导诊系统源码:解决患者盲目就诊问题、降低患者挂错号比例
    安装RPM包或源码包
    基于低代码平台的PLM系统,实现科学业务管理
    ubuntu 18 更新git版本到 2.80.1
    Python交叉验证实现
    冷链物流行业市场调研 冷链物流将朝着智慧化方向发展
    扩展期权定价模型到二元期权定价
    谷粒商城-前端开发基础知识
    Ajax——AJAX实现省市联动
    【Mybatis】使用IDEA创建第一个Mybatis入门程序
  • 原文地址:https://blog.csdn.net/weixin_45800628/article/details/126360692