zoukankan      html  css  js  c++  java
  • C#和Python 图片和base64的互转

    C#实例代码:

    /// <summary>
    /// 图片转base64
    /// </summary>
    /// <param name="bmp"></param>
    /// <returns></returns>
    private string ImgToByte(Bitmap bmp)
    {
    string result;
    try
    {
    //Image bmp = new Bitmap(filename);
    MemoryStream memoryStream = new MemoryStream();
    bmp.Save(memoryStream, ImageFormat.Jpeg);
    byte[] array = new byte[memoryStream.Length];
    memoryStream.Position = 0L;
    memoryStream.Read(array, 0, (int)memoryStream.Length);
    memoryStream.Close();
    result = Convert.ToBase64String(array);
    }
    catch (Exception ex)
    {
    result = null;
    }
    return result;
    }

    /// <summary>
    /// base64转图片
    /// </summary>
    /// <param name="base64string"></param>
    /// <returns></returns>
    public Bitmap GetImageFromBase64(string base64string)
    {
    byte[] b = Convert.FromBase64String(base64string);
    MemoryStream ms = new MemoryStream(b);
    Bitmap bitmap = new Bitmap(ms);
    return bitmap;
    }

    注:

    使用birmap类型,需要在引用右键 -> 添加引用 -> 程序集 搜索 system.drawing 添加即可

    python实例代码:

    import base64
    # 将base64转为图片并保存到指定位置
    filepath = 'data/image.jpg'
    imagedata = base64.b64decode(imgbase64)
    file = open(filepath, "wb")
    file.write(imagedata)
    file.close()

    将图片转为base64

    with open('data/cs1.jpg', 'rb') as f:  # 以二进制读取图片
    data = f.read()
    encodestr = base64.b64encode(data) # 得到 byte 编码的数据
    cs = str(encodestr, 'utf-8')
  • 相关阅读:
    oracle误操作commit之后,可以闪回数据
    删除表中重复数据,只保留一条数据
    去掉表中字段空的空格或换行符
    oracle主键自增
    List
    Collection Iterator 迭代器
    oracle 处理表的一列
    java swing
    oracle 常用函数大全
    cf 40A
  • 原文地址:https://www.cnblogs.com/xiewei123/p/10902481.html
Copyright © 2011-2022 走看看