将位图数据转换为图像标记格式

时间:2014-01-29 09:04:43

标签: asp.net bitmapdata

我有创建缩略图的功能:

Image photo=System.Drawing.Image.FromStream(myFile.InputStream);

Bitmap bmp = new Bitmap(100, 100);
Graphics graphic = Graphics.FromImage(bmp);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(photo, 0, 0, 100, 100);

bmp图像将采用位图格式 如何转换它,以便在图像标签中分配并在页面上显示?

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式返回字节数组。

MemoryStream stream = new MemoryStream();
bmp.Save(stream, ImageFormat.Jpeg);
Byte[] buffer = new byte[0];
buffer = stream.ToArray();
return buffer;

并使用通用处理程序,您可以在图像标记中显示此数据。

答案 1 :(得分:0)

我根据几个想法构建了一个片段,这非常有效:

 Bitmap original = new Bitmap(@"C:\path\img.jpg");
 Rectangle srcRect = new Rectangle(0, 0, 100, 100);
 Bitmap cropped = (Bitmap)original.Clone(srcRect, original.PixelFormat);
 byte[] imgbytes;    
 using (MemoryStream stream = new MemoryStream())
 {
        cropped.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        imgbytes = stream.ToArray();
 }
 <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(imgbytes))" />

在矩形内,偏移量为(0,0)并从原始位置裁剪100x100像素。