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.
You are serializing Bitmap to response stream. Your JS will receive a .net serialized object of type System.Byte[]
and not a Base64 encoded string.
MemoryStream.ToArray()
Convert.ToBase64String(bitmapBytes)
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.