手机上传图片横向显示,根据需要进行旋转。


左图为旋转后,右图为旋转前。


不管是做wap还是H5时,通过手机端上传的图片,在部分安卓机器上会出现图片横向显示,不管手机是竖着拍照还是横着拍照,都无法避免,

具体原因还不清楚,目前经过测试觉得应该图片文件问题,缺少exif头文件,可通过软件来验证。


本来是想通过获取图片的exif图文件来确定哪些图片需要旋转,怎么旋转的,百度后发现,有些设备拍出来的图片,竟然没有exif头文件,

这条路就走不通了,发挥自己的思维,正常的图片都是竖向的,也就是宽度小于高度,如果服务器接收到图片,保存下来,这时判断图片的宽度和高度的大小,如果宽度大于高度,是不是就可以确认此图片就需要旋转呢,可能不严谨,因为,我现在遇到的问题就是这样的,并且只需要顺时针旋转90度即可。


如果需要更复杂的判断、旋转,可在此基础完善。

旋转图片的事件:

string ImageUrl = imgRate.ImageUrl;
System.Drawing.Bitmap bit = new Bitmap(Server.MapPath(ImageUrl));
        
if(bit.Width> bit.Height)
{
    bit = KiRotate(bit, 90, Color.White);
    string imgname = Common.GetGuid() + ".jpg";
    string FilePath = Server.MapPath(imgname);//转换物理路径
    bit.Save(FilePath);
}
可以做一个按钮事件,点击后,你会发现旋转后的图片已经出现了。

下边是核心方法:

/// <summary>
/// 任意角度旋转
/// </summary>
/// <param name="bmp">原始图Bitmap</param>
/// <param name="angle">旋转角度</param>
/// <param name="bkColor">背景色</param>
/// <returns>输出Bitmap</returns>
public static Bitmap KiRotate(Bitmap bmp, float angle, Color bkColor)
{
    int w = bmp.Width + 2;
    int h = bmp.Height + 2;

    PixelFormat pf;

    if (bkColor == Color.Transparent)
    {
        pf = PixelFormat.Format32bppArgb;
    }
    else
    {
        pf = bmp.PixelFormat;
    }

    Bitmap tmp = new Bitmap(w, h, pf);
    Graphics g = Graphics.FromImage(tmp);
    g.Clear(bkColor);
    g.DrawImageUnscaled(bmp, 1, 1);
    g.Dispose();

    GraphicsPath path = new GraphicsPath();
    path.AddRectangle(new RectangleF(0f, 0f, w, h));
    Matrix mtrx = new Matrix();
    mtrx.Rotate(angle);
    RectangleF rct = path.GetBounds(mtrx);

    Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
    g = Graphics.FromImage(dst);
    g.Clear(bkColor);
    g.TranslateTransform(-rct.X, -rct.Y);
    g.RotateTransform(angle);
    g.InterpolationMode = InterpolationMode.HighQualityBilinear;
    g.DrawImageUnscaled(tmp, 0, 0);
    g.Dispose();

    tmp.Dispose();

    return dst;
}





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值