2011-05-05 35 views
-2

我有十六進制數據,我想將其轉換爲200x200像素灰度圖片,但我找不到一種方法來做到這一點。從十六進制數據繪製灰度圖片

任何人都可以請給我一個方法或給我一個資源來解決這個問題?

+1

請解釋一下你正在試圖做的好一點什麼。圖像是否應該以選定的字體/字體大小顯示給定的文字? – 2011-05-05 11:04:39

+0

ascii數據如何與像素顏色相關?你的數據如何? – Marco 2011-05-05 11:06:41

+0

對不起,我誤以ascii與十六進制,,我的任務在學校實際上要求我從十六進制數據做灰度圖...你能幫我嗎,我真的很迷惑, – ecaiseng 2011-05-13 17:50:10

回答

3

對於你寫的(太少)你可以創建Bitmap bmp = new Bitmap(200,200)
然後你可以根據你的文本數據使用bmp.SetPixel(x,y,color)

UPDATE
假設了很多事情:

  • 你有hexstr包含代表您的BMP十六進制數據
  • hexstr由兩個字符組(十六進制數據)
  • 每個十六進制數據組的長度都是2或6個字符(如果十六進制值val已經是灰度值,則爲2個字符,如果您有RGB值轉換爲灰色,則爲6個字符凱爾)

第二次更新
您的文件contanins 16x2450 = 39200像素,讓你的形象不能200x200的。我認爲它是200x192。
此代碼的工作,即使我不明白什麼樣的形象代表......

你可以試試這個:

public Form1() 
{ 
    InitializeComponent(); 
    string hexstr = FileToHexStr(path_to_file); 
    pictureBox1.Image = ConvertToBmp(hexstr, 200, 196, true); 
} 

private string FileToHexStr(string filename) 
{ 
    StringBuilder sb = new StringBuilder(); 
    string[] f = File.ReadAllLines(filename); 
    foreach (string s in f) sb.Append(s.Trim().Replace(" ", "")); 
    return sb.ToString(); 
} 

private byte[] StringToByteArray(string hex) 
{ 
    return Enumerable.Range(0, hex.Length) 
        .Where(x => x % 2 == 0) 
        .Select(x => System.Convert.ToByte(hex.Substring(x, 2), 16)) 
        .ToArray(); 
} 

private Bitmap ConvertToBmp(string hexstr, int width, int height, bool isGrayScaleString) 
{ 
    /// If hexstr is a color bitmap I assume that a single pixel 
    /// must be 3 values long (one for R, one for G, one for B); 
    /// if not, then every hex value is a pixel 
    int bpp = isGrayScaleString ? 1 : 3; 
    byte[] hexarr = StringToByteArray(hexstr); 
    // Check if string is correct 
    if (hexarr.Length != (width * height * bpp)) return null; 

    Bitmap bmp = new Bitmap(width, height); 
    int index = 0; 
    for (int i = 0; i < hexarr.Length; i += bpp) 
    { 
     int luma = (int)(isGrayScaleString ? 
      hexarr[index] : 
      // Formula to convert from RGB to Grayscale 
      // <see>http://www.bobpowell.net/grayscale.htm</see> 
      0.3 * hexarr[i] + 0.59 * hexarr[i + 1] + 0.11 * hexarr[i + 2]); 
     Color c = Color.FromArgb(luma, luma, luma); 
     bmp.SetPixel(index % width, index/width, c); 
     index++; 
    } 
    return bmp; 
} 
+0

@marco:對不起,這裏的互聯網連接非常糟糕,我試試你的代碼它ru ñ順利),並做一些實驗,我在網站上發現的代碼早些時候..但我不能讓它進入[形式設計](http://www.mediafire.com/?vby4p2dm3qddk11)我打算使用,, – ecaiseng 2011-05-15 22:35:21

+0

@marco:我應該使用picturebox方法嗎?當我使用action按鈕將我的十六進制數據轉換爲圖像時,代碼顯示錯誤編譯...這是我根據您的代碼嘗試的代碼... – ecaiseng 2011-05-15 22:41:26

+0

@ marco:它顯示錯誤在** buttonconvert_Click **方法&** buttonconvert **在線位圖bmp = buttonconvert(hexstr,200,200,isGrayScale)... – ecaiseng 2011-05-15 22:57:10