我遇到了错误: 无法从具有索引像素格式的图像创建图形对象
所以我将此代码实现到我的方法中:Solution for "A Graphics Object cannot be Created from an Image that has an Indexed Pixel Format"
但现在我的水印并不想画出我的形象。
请任何人协助。
代码:
private Image AddWaterMark(Image original)
{
Image waterMark = Image.FromFile(ConfigurationManager.AppSettings["GalleryFolder"] + @"\watermark.png");
Bitmap bm = (Bitmap)original;
Size waterMarkResize = ResizeFit(new Size(original.Width, original.Height));
using (Image watermarkImage = new Bitmap(waterMark, waterMarkResize))
using (Graphics imageGraphics = Graphics.FromImage(new Bitmap(bm.Width, bm.Height)))
{
imageGraphics.DrawImage(bm, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel);
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (original.Width / 2 - watermarkImage.Width / 2);
int y = (original.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
}
}
return bm;
}
答案 0 :(得分:3)
您正在创建新的Bitmap
以传递给Graphics.FromImage
,然后返回未编辑的原始Bitmap
。单独创建新的Bitmap
,将其传递给FromImage
,然后返回新的Bitmap
。
var edit = new Bitmap(bm.Width, bm.Height);
// ...
using (Graphics imagesGraphics = Graphics.FromImage(edit))
{
// draw original
// draw watermark
}
return edit;