我在下面编写代码,我有 image2 是某处的图片,而 image3 是白色平面中的文本(例如,在默认白色背景中用paint.exe 编写的“你好”)。
我想在图片上显示文字,但代码不成功。问题是什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace test_AlignmentOFImages
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WriteableBitmap bitmap;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
byte []pixels=new byte[480*640*4];
for (int i = 0; i < pixels.Length; i++)
{
if (i % 16 == 0)
{
pixels[i] = 0xff;
}
else
{
pixels[i] = (byte)i;
}
//pixels[i] = (byte)0xff;//white
}
int stride2 = 480 * 4;
image2.Source = BitmapImage.Create((int)image2.Width, (int)image2.Height, 96, 96, PixelFormats.Bgra32, null, pixels, stride2);
byte [] imagePixels=new byte[480*640*4];
System.Drawing.Image img;
//System.Drawing.Bitmap bm;
try
{
//img = System.Drawing.Image.FromFile(@"E:\src\Tests\test_AlignmentOFImages\test_AlignmentOFImages\image3.jpg");
img = System.Drawing.Image.FromFile(@"E:\src\Tests\test_AlignmentOFImages\test_AlignmentOFImages\image3.png");
}
catch (Exception ex)
{
throw ex;
}
MemoryStream ms=new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Array.Copy(ms.ToArray(), imagePixels, ms.ToArray().Length);
byte[] imagePixels2 = new byte[480 * 640*4];
image3.Source = null;
for (int i = 0; i < imagePixels.Length; i+=4)
{
if (imagePixels[i]<0xff )//if it is not white
{
imagePixels2[i] = imagePixels[i];//blue
imagePixels2[i+1] = imagePixels[i+1];//green
imagePixels2[i+2] = imagePixels[i+2];//red
imagePixels2[i+3] = 0xff;//alpha
}
}
image3.Source = BitmapImage.Create((int)image3.Width, (int)image3.Height, 96, 96, PixelFormats.Bgra32, null, imagePixels2, stride2);
}
}
}
我认为我使用的是错误像素格式,对于 png 或 jpeg 格式,我必须使用特殊的像素格式(例如 bgr24 或 ...)。提前致谢。