1

asp.net c# で base64 文字列を画像に変換するタスクがあり、次のコードを使用しています。

private static bool SaveImage(string path, string link, string name)
{
    bool result = true;
    if (link.StartsWith("data:image/jpeg;base64,"))
    {
        try
        {
            string intImg = path + "/" + name + ".jpg";
            System.Drawing.Image bmpFromString = Base64StringToBitmap(link.Replace("data:image/jpeg;base64,",""));
            bmpFromString.Save(intImg, ImageFormat.Jpeg);
            result = true;
        }
        catch (Exception)
        {
            result = false;
        }
    }
    return result;
}

public static System.Drawing.Image Base64StringToBitmap(string base64String)
{
    System.Drawing.Image bmpReturn = null;
    //string converted = base64String.Replace('-', '+');
    //converted = converted.Replace('_', '/');
    byte[] byteBuffer = Convert.FromBase64String(base64String);
    using (MemoryStream memoryStream = new MemoryStream(byteBuffer))
    {
        //finalImage = System.Drawing.Image.FromStream(ms);
        memoryStream.Position = 0;
        bmpReturn = System.Drawing.Image.FromStream(memoryStream);
        memoryStream.Close();
        byteBuffer = null;
    }
    return bmpReturn;
}

これは base64 文字列です

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAGQAZAMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAEAAMFBgcBAv/EADsQAAIBAwMBBQYCCQMFAAAAAAECAwAEEQUSITEGEyJBUQcUYXGBkaHRFSMyQoKxwfDxUmKiJTOSsuH/xAAaAQACAwEBAAAAAAAAAAAAAAAEBQECAwYA/8QAKhEAAgICAQMCBgIDAAAAAAAAAAECAwQREhMhMQVRIjIzQXGBkdEUNEL/2gAMAwEAAhEDEQA/ANI4qr6p7Q+zmm3DW8l1LLIhw3cwllH16H6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So6OMgBuaR5VMciHWq/YWk0xm5sY5pJt67t9uUJI6/wB5rJLU5tWRsFhlSfTHH9K1lrl2eWRcbIkbcCcEn0H9+YrH7CeO5FxJG26IzSFD0ypY4NNvSOXQSYJmrWiPtzIJn24XDZzgbjRjM+MFiTjNCSJJ7y/dsxY/ugAgfHNPNujjPeSF2xjkAfypsLwe4PeNgnPFBWIxdO2VyFx145/xRa9WJ8hUdYNv71h8P5V5HmHvMQx5rtMY9RSqxAE9xG3SRfvTMrofMGuGNE4GDTckgAwAM1Qk8I7KCodlU8kDzrYfY1CP0JcTjrJcNn44AH51jgOa2z2Prt7LKcdZXP8AyP5Us9WesV/lBeJ3t/Rd7qNJ4WRwGBGMGs1vobjsvqErwq7WknIVTwp+VaS5ySPKofWbKO7hKsBnyNc3i5DonteBxFdtMpuodotTvLJksFAZ03K279psdOvT+oJ44xTOx8ostcSHUI2eJAQYH4G7IHIPHn51ebux9yjznndgVnWuFo9dnlQ4IkDA/wAK10mHkdbaS0hfmRUZRkXrtjqMFzaWrW1uYdsu3gKOCpOMDp0/lVVd9wqPN7PKipKwAjHHGc/j/eaF/Sko47pPqTTCtOMdMCukpz2iXVS47tThn8IPxPFRlrFLZyyRTjbztDHgEgdM/Ig09pd7JcajAjhUXJOEB5ODT3aCaOWzjMR6yhzxjOVOD+FVdklYo67FVBODewaSaTd4FJHqKVQ+cUq3MdhJNeFjDrKTnwx7h8812lVS4yv7Nbl7KAB2Rgx/rf8A9jSpUq9Y/wBf9oLwvqFvfzoC4J2/WlSrlV5HCKt2xUPp4U/6g3HqDms11OJV1CaPJYdcnrzXKVdP6T9P+RZnfMBL/wBon5igW/bNKlTgAJbs7GrXLMeqbSD88

エラーメッセージは、

Error Message The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "

この方法の何が問題なのか理解できません。間違っている場合は誰かが修正してくれますか。

4

2 に答える 2