简体   繁体   中英

Save image from result convert base64 string in asp.net core

Before i already make method in webservice and it is my coding

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Base64ToImage(string imagestr)
{
    DbAccessConnection conn = getActiveConnection();

    try
    {
        beginTransaction(conn);

        string DefaultImagePath = HttpContext.Current.Server.MapPath("~/c:/image");

        byte[] bytes = Convert.FromBase64String(imagestr);

        using (MemoryStream ms = new MemoryStream(bytes))
        {
            Image pic = Image.FromStream(ms);

            pic.Save(DefaultImagePath);
        }
            commitTransaction(conn);
    }
    catch (Exception ex)
    {
        rollbackTransaction(conn);

        Responder.writeResponse(false, ex.Message);             
    }
}

And i got message error when i execute method Base64ToImage in my webservice This is a message error

{"isSuccess":false,"resultMessage":"A generic error occurred in GDI+.","data":null}

Please help me, how i can fix ?

There is a bug in your code, DefaultImagePath is a directory, you have to specify a file name for Save() method to actually work.

For example:

// Example 1:
pic.Save("full/path/to/your/image.jpg");

// Example 2:
pic.Save(DefaultImagePath + "/yourimage.jpg");

Probably you might have missed the format of image while saving, and file name should be complete (not folder path)

pic.Save(DefaultImagePath,ImageFormat.Png);

rewrite like

using (MemoryStream ms = new MemoryStream(bytes))
        {
            using (Image pic = Image.FromStream(ms))
            {
             pic.Save(DefaultImagePath+fileName.png, ImageFormat.Png);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM