有问题将32位图像转换为双色黑白

时间:2013-09-23 16:00:13

标签: .net wpf vb.net image-processing imaging

我有以下代码例程......

Public Shared Sub ConvertToBitonal(ByRef Source As System.Windows.Media.Imaging.WriteableBitmap)
    If Source.Format = System.Windows.Media.PixelFormats.BlackWhite Then
        Exit Sub
    End If

    Dim BytesPerPixel As Integer = (Source.Format.BitsPerPixel + 7) / 8
    Dim Stride As Integer = Source.PixelWidth * BytesPerPixel
    Dim NumBytes As Long = Source.PixelHeight * Stride
    Dim pixels As Byte() = New Byte(NumBytes - 1) {}

    Source.CopyPixels(pixels, Stride, 0)

    For cnt As Integer = 0 To pixels.Length - 1 Step BytesPerPixel
        Dim blue As Byte = pixels(cnt + 0)
        Dim green As Byte = pixels(cnt + 1)
        Dim red As Byte = pixels(cnt + 2)
        Dim intensity As Integer = CType(red, Integer) + CType(green, Integer) + CType(blue, Integer)
        Dim targetColor As Byte

        If intensity > 400 Then
            targetColor = 255
        Else
            targetColor = 0
        End If

        pixels(cnt + 0) = targetColor
        pixels(cnt + 1) = targetColor
        pixels(cnt + 2) = targetColor
        pixels(cnt + 3) = targetColor
    Next

    Source.WritePixels(New System.Windows.Int32Rect(0, 0, Source.PixelWidth, Source.PixelHeight), pixels, Stride, 0)
End Sub

当源图像是每像素24位的时候,输出完全按照我想要的方式输出,但是当源图像是32位时,颜色不会变得坚固,我会在整个图像中运行垂直线。有人可以告诉我如何修改例程,使32位图像像24位计数器部分一样出现吗?

这是我正在谈论的屏幕截图...(显然我还没有足够的代表发布图片所以这里是一个链接

enter image description here

2 个答案:

答案 0 :(得分:0)

您可能必须先创建一个24bpp的图像副本。你试过了吗?

我很久以前做了类似的事情(很久以前就回忆起细节),这篇文章很有帮助:Bitonal conversion issues。 MSDN论坛上也有一些信息。

编辑:seen this entry?

答案 1 :(得分:0)

我挖掘代码并查看问题:

Dim BytesPerPixel As Integer = (Source.Format.BitsPerPixel + 7) / 8

删除+ 7

同样改变这个:

    pixels(cnt + 0) = targetColor

    pixels(cnt + 1) = targetColor

    pixels(cnt + 2) = targetColor

    pixels(cnt + 3) = targetColor

到包含步骤的FOR循环........:

        Dim x%

        For x = cnt To cnt + BytesPerPixel - 1

            pixels(x) = targetColor

        Next

如果步骤是> 4,它不会设置值,并会给你这个栏。