2012-09-02 12 views
3

我想將用戶輸入的字符串轉換爲image..how可以完成嗎? 我試過下面的代碼,但我得到一個參數異常的行: WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);將字符串轉換爲C#中的圖像用於Windows Phone 7應用程序

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()); 

     } 

    } 

我得到了我在以下鏈接想.. How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7?http://blogs.u2u.be/michael/post/2011/04/20/Adding-a-text-to-an-image-in-WP7.aspx感謝所有誰回答初始幫助! :)

+0

我很困惑,目標是什麼?用戶將輸入一個很長的序列非人類可讀的字節轉換爲JPG?或者你是否試圖做一些事情,比如讓他們輸入「你好」,然後用該文本創建一個圖像?兩件完全不同的事情。 –

+1

有些人會讓他們進入「你好」,並用該文本創建一個圖片。那就是目標。 – shubhi1910

+3

啊好的,那麼你是相當方法:)你基本上需要使用內部繪圖API來完成你想要的 - 這個參考可能是一個開始:http://writeablebitmapex.codeplex.com/ –

回答

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讓我知道,如果你需要說明的任何細節。

+1

嘿,我想system.drawing不存在的Windows手機。 – shubhi1910

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); 
    } 

這裏我轉換文本塊文成位圖,然後將其分配給圖像源。

相關問題