Home » Javascript » C# Bitmap to Html img using ajax doesn't work

C# Bitmap to Html img using ajax doesn't work

Posted by: admin October 29, 2018 Leave a comment

Questions:

This is my C# code to make Bitmap

   public void VerificationCode(int captchaWidth = 75, int captchaHeight = 25)
    {

        var colorList = new List<Color> { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Brown };


        Response.ContentType = "image/gif";

        Response.Clear();

        Response.BufferOutput = true;


        var randString = new Random((int)DateTime.Now.Ticks).Next(99999).ToString("00000");     

        Session["VerificationCode"] = randString;

        var bitmap = new Bitmap(captchaWidth, captchaHeight);            
        var graph = Graphics.FromImage(bitmap);            
        var font = new Font("Arial", 16, FontStyle.Italic);

        var fontColor = Color.FromArgb(153, 153, 153);            
        graph.Clear(Color.White);            
        graph.DrawString(randString, font, new SolidBrush(fontColor), 0, 0);

        var random = new Random((int)DateTime.Now.Ticks);
        var randomColor = new Random((int)DateTime.Now.Ticks);

        for (var i = 0; i < 100; i++)
        {
            var c = randomColor.Next(0, colorList.Count);
            var randPixelX = random.Next(0, captchaWidth);
            var randPixelY = random.Next(0, captchaHeight);
            bitmap.SetPixel(randPixelX, randPixelY, colorList[c]);
        }            
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
    }



 $('#ChangeCaptcha').on('click', function () {
        $.ajax({
            url: '@Url.Action("VerificationCode", "Base")',
            type: 'Get',
            async: false,
            success: function (data) {
                console.log(data);
                $('#CaptchaImage').attr('src', "data:image/gif;base64," + data);
            }
        });
    });

This is my Javascript code using ajax to get Bitmap to change img src.
But It’s doesn’t work.I alway get error message. Could any one can help me to fix this issue. I have used change minitype to “data:image/bmp;base64” or “data:image/gif,” then I always get error.

enter image description here

Answers: