【C#】【WriteableBitmap】保存图像到本地

/// <summary>
/// 保存图像到本地
/// </summary>
/// <param name="wtbBmp"></param>
/// <param name="name"></param>
/// <param name="strDir"></param>
/// <returns></returns>
public static string SaveBitmap(WriteableBitmap wtbBmp, string name, string strDir = "Picture\\")
{
    if (wtbBmp == null)
    {
        return null;
    }

    ushort channels = (ushort)(wtbBmp.BackBufferStride / wtbBmp.PixelWidth);
    if (channels == 3)
    {
        wtbBmp = ImageHelper.ConvertBitmap24To8(wtbBmp);
    }

    string result;
    try
    {
        BmpBitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
        bitmapEncoder.Frames.Add(BitmapFrame.Create(wtbBmp));

        string strpath = strDir + name + ".bmp";

        if (!Directory.Exists(strDir))
        {
            Directory.CreateDirectory(strDir);
        }
        if (!File.Exists(strpath))
        {
            using (FileStream a = File.OpenWrite(strpath))
            {
                bitmapEncoder.Save(a);
                a.Close();
            }
        }
        else
        {
            DebugOutput.ProcessMessage($"图片保存失败 strpath: {strpath}");
        }
        result = strpath;
    }
    catch (Exception ex)
    {
        DebugOutput.ProcessMessage("图片保存失败:"+ ex);
        result = null;
    }
    return result;
}
posted @ 2024-05-20 11:35  qiutian-hao  阅读(167)  评论(0编辑  收藏  举报