3

我想将用户输入的字符串转换为图像..怎么做?我尝试了以下代码,但我在该行中得到一个参数异常:WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);

    static public string EncodeTo64(string toEncode)
    {
        byte[] toEncodeAsBytes
              = StringToAscii(toEncode);
        string returnValue
              = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }

    public static byte[] StringToAscii(string s)
    {
        byte[] retval = new byte[s.Length];
        for (int ix = 0; ix < s.Length; ++ix)
        {
            char ch = s[ix];


            if (ch <= 0x7f)  retval[ix] = (byte)ch; 
            else  retval[ix] = (byte)'?'; 
        }

        return retval;
    }
    void convert()
    {
        String s = textBox1.Text;
        byte[] data = Convert.FromBase64String(EncodeTo64(s));

        for (int i = 0; i < data.Length; i++)
        {
            System.Diagnostics.Debug.WriteLine(data[i]);
        }
        Stream memStream = new MemoryStream();
        memStream.Write(data, 0, data.Length);


        try
        {
        WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);

        image1.Source = wbimg;
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());

        }

    }

我在以下链接中得到了我想要的东西。在 Windows Phone 7 中,如何在后台线程上的 WriteableBitmap 上呈现文本?http://blogs.u2u.be/michael/post/2011/04/20/Adding-a-text-to-an-image-in-WP7.aspx感谢所有回复最初帮助的人!:)

4

2 回答 2

2

这是您可以将TextBlock 文本转换为图像的简单方法

    private void convert_Click(object sender, RoutedEventArgs e)
    {
        Canvas c1 = new Canvas();
        TextBlock t = new TextBlock();
        t.Text = text1.Text;
        t.FontFamily = text1.FontFamily;
        t.Foreground = text1.Foreground;
        t.FontSize = text1.FontSize;
        c1.Children.Add(t);
        WriteableBitmap wbmp = new WriteableBitmap(c1, null);
        im = new Image();
        im.Source = wbmp;
        im.Height = 200;
        im.Width = 200;     
        Canvas.SetTop(im, 10);
        Canvas.SetLeft(im, 10);

        Main_Canvas.Children.Add(im);
    }

这里我将 Textblock Text 转换为 Bitmap,然后将其分配给图像源。

于 2013-04-30T06:04:51.723 回答
1

以下是如何将字符串写入位图:

        Bitmap b = new Bitmap(200, 100);
        Graphics g = Graphics.FromImage(b);
        g.DrawString("My sample string", new Font("Tahoma",10), Brushes.Red, new Point(0, 0));
        b.Save("mypic.png", System.Drawing.Imaging.ImageFormat.Png);
        g.Dispose();
        b.Dispose();

如果您需要解释任何细节,Shubhi1910 让我知道。

于 2012-09-03T08:09:25.707 回答