为每种颜色定义代码

时间:2013-03-23 08:31:54

标签: vb.net graphics drawing

有没有办法为每种颜色归属代码,并能够阅读它们?我的意思是编程。 我的目标是将图像转换为代码,然后将其转换回图像。

2 个答案:

答案 0 :(得分:0)

每种颜色都有4个字段(对于某些图像,您只有3个字段包含有意义的信息)

这些字段包括:

  • Alpha(A)(这表示像素的不透明度)
  • 红色(R)(红色强度)
  • 绿色(G)(绿色强度)
  • 蓝色(B)(蓝色强度)

你要做的就是阅读它们,并通过将值相互连接为每个代码字符串生成一个代码字符串。

这很可能被认为是伪代码,因为我没有检查它是否编译,但你应该按照这一点做一些事情。

Dim pixelColor As Color
Dim image As BitMap = New BitMap("your_image.png")

Dim a As String
Dim r As String
Dim b As String
Dim g As String

Dim fileString As New StringBuilder()

fileString.AppendLine(image.Size.Width.ToString())
fileString.AppendLine(image.Size.Height.ToString())

' Loop over all pixels
For y As Integer = 0 To image.Size.Height - 1
    For x As Integer = 0 To image.Size.Width - 1
        pixelColor = image.GetPixel(x, y)

        ' get ARGB values as strings
        a = pixelColor.A.ToString()
        r = pixelColor.R.ToString()
        g = pixelColor.G.ToString()
        b = pixelColor.B.ToString()

        ' Append the colors, one pixel per line
        fileString.AppendLine(a & " " & r & " " & g & " " & b)
    Next
Next

Using file As New StreamWriter("image_data.txt")
    outfile.Write(fileString.ToString())
End Using

同样,这可能无法编译。 (目前我没有编译器)

修改 我意识到宽度和高度也需要存储。


至于阅读文件:

Dim file As System.IO.StreamReader
file = File.OpenText("text_file.txt")

Dim width As Integer = Convert.ToInt32(file.ReadLine)
Dim height As Integer = Convert.ToInt32(file.ReadLine)

Dim image As BitMap = New BitMap(width, height)

Dim currentX As Integer = 0
Dim currentY As Integer = 0

Do Until file.EndOfStream
    Dim line As String = file.ReadLine

    Dim valueArray(4) As String = line.Split(" ")

    Dim a As Integer = Convert.ToInt16(valueArray(0))
    Dim r As Integer = Convert.ToInt16(valueArray(1))
    Dim g As Integer = Convert.ToInt16(valueArray(2))
    Dim b As Integer = Convert.ToInt16(valueArray(3))

    image.SetPixel(currentX, currentY, Color.FromArgb(a, r, g, b))

    currentX = currentX + 1

    If currentX == width Then
        currentX = 0
        currentY = currentY + 1

        If currentY == height Then
            Exit Do ' We're done here.
        End If
    End If
Loop

' At this point, you'll have a BitMap with all the pixels set.

再次考虑这个伪代码。

答案 1 :(得分:0)

每种颜色实际上是ARGB颜色代码,只需获取整数值

Dim myColor As Color = Color.Red
Dim Code As Integer = myColor.ToArgb()

Dim myColorBack As Color = Color.FromArgb(Code)