【问题标题】:Image manipulation图像处理
【发布时间】:2011-04-22 06:15:43
【问题描述】:

我需要一种易于学习且快速的方法来从背景图像、文本生成图像,然后保存为 JPEG 格式。

你有什么建议?任何关于此的图书馆或教程?重要的标准是简单。

【问题讨论】:

  • “来自背景图片的图片,文本”是什么意思?截图?

标签: c# image-processing image-manipulation


【解决方案1】:

GDI+ 和 System.Drawing 命名空间是做你想做的事所必需的。下面是一个基本示例,但网上有很多资源详细介绍了更高级的功能:

using(Bitmap myBitmap = new Bitmap("C:\\backgroundImage.jpg"))
using(Graphics g = Graphics.FromImage(myBitmap))
{
   g.DrawString("Text", new Font("Arial", 10), Brushes.White, new PointF(0, 0));
   myBitmap.Save("C:\\newImage.jpg");
}

【讨论】:

  • 您应该始终处置 GDI+ 对象,例如使用“使用”结构。否则可能会导致停顿。
  • -1:这对我几分钟前发布的答案没有任何帮助,此外还省略了 Skrim 也评论过的至关重要的 GDI+ 对象的处置。
  • @Øyvind 当您最初发布您的答案时,您没有包含任何有关添加问题中指定的文本的内容。为什么这么刻薄?
  • @Skrim 好点,我添加了必要的 Dispose 调用以使这一点显而易见。
  • @Andy:这样做还是有问题的。例如,如果 myBitmap.Save 引发异常,您的 Dispose 语句将永远不会运行。您应该对它们使用 Using 块,或者将它们放入 try/finally 块中。
【解决方案2】:

在 .Net 3.5/4 中,您还可以使用 WPF/Media.Imaging 作为 GDI+ 的替代品

首先创建一个DrawingVisual和一个DrawingContext:

DrawingVisual visual = new DrawingVisual();
DrawingContext dc = visual.RenderOpen();

然后在上面画东西:

dc.DrawRectangle(...);
dc.DrawText(...);
etc...

确保关闭它:

 dc.Close();

WPF 的伟大之处在于 GUI 中的所有内容实际上也是一个视觉对象,因此,如果您希望不必使用上面的代码以编程方式进行绘制,您实际上可以在窗口上的 xaml 中构建您的视觉对象,然后然后直接渲染到RenderTargetBitmap。

一旦您构建了视觉效果,您就可以使用编码器将其渲染到文件中(.Net 有用于Jpeg、Png、Bmp、Gif、Tiff 和 Wmp 的编码器)。

// Create a render target to render your visual onto. The '96' values are the dpi's, you can set this as required.
RenderTargetBitmap frame = new RenderTargetBitmap((int)visual.ContentBounds.Width, (int)visual.ContentBounds.Height, 96, 96, PixelFormats.Pbgra32);
frame.Render(visual);

// Now encode the rendered target into Jpeg and output to a file.
JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
jpeg.Frames.Add(BitmapFrame.Create(frame));
using (Stream fs = File.Create(@"c:\filename.jpg"))
{
    jpeg.Save(fs);
}

Drawing Objects 和 WPF Graphics Rendering 上有一些很好的 MS 教程。

【讨论】:

    【解决方案3】:

    您可以使用更现代(通常更快)的System.Windows.Media.Imaging API,而不是旧的 GDI+。

    【讨论】:

      【解决方案4】:

      我通常使用GDI+ 来执行此操作。网上有很多这方面的教程,但基本上你需要做的是这样的:

      using(Image image = new Bitmap(Width, Height))
      using (Graphics g = Graphics.FromImage(image)) {
        g.Draw....
        g.Draw....
        image.Save(filename, ImageFormat.Jpeg);
      }
      

      对Draw.... 的调用可以绘制图元、图像、文本等。

      还要记住,文本看起来是锯齿状的,你可以在 Graphics 对象上使用方法来平滑它。在这种情况下g.TextRenderingHint = TextRenderingHint.AntiAlias;

      如果您觉得它是锯齿状的,还有其他选项可以使它看起来更好。默认设置更注重性能而不是质量,所以如果你想要高质量,你需要自己设置。 g.SmoothingMode 设置为例如 HighQuality 将使您的圆形基元看起来比默认配置更平滑。

      它真的很容易使用,并且可以使最终图像看起来像你想要的那样,所以试试吧!

      【讨论】:

      • 如果看起来有块状,请在 jpeg 保存时设置更高的质量
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2015-08-09
      • 2015-09-07
      相关资源
      最近更新 更多