2012-10-17 37 views
0

「OFD是打開文件對話框DirectCast不工作​​

Dim img As Bitmap 
Dim iscmyk As Boolean 
Dim i As String 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 


    ofd.Filter = "Jpg Image(*.jpg)|*.jpg" 
    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then 
     img = Bitmap.FromFile(ofd.FileName) 
     iscmyk = ((DirectCast(img.Flags, Imaging.ImageFlags) And Imaging.ImageFlags.ColorSpaceCmyk) = Imaging.ImageFlags.ColorSpaceCmyk) 
    End If 
    img = New Bitmap(img, New Size(120, 190)) 
    MsgBox("cmyk = " & iscmyk) 
    PictureBox1.Image = img 
End Sub 

我需要檢查,如果圖像是CMYK或RGB 如果CMYK然後iscmyk返回true 如果它不是那麼CMYK iscmyk在返回false 我Windows 7的PC其返回false每個&每個圖像 但在XP它返回完美的答案

爲什麼它不在我的其他的win7電腦工作???

+0

你說DirectCast不工作​​。你有錯誤嗎?該行被執行時,img.Flags的值是多少? –

+0

不是沒有得到錯誤,但它給出了錯誤的結果 – Dandy

+0

我試圖CInt而不是直接播放,但CInt不工作在XP – Dandy

回答

2
  • 首先,對不起,應對這麼晚...
  • 二,其實我不知道 爲什麼你在不同的操作系統版本不同的結果。

無論如何,這裏是一個低級(和醜陋)的解決方法。它是專爲JPEG圖像:

Public Shared Function GetJpegBpp(FileName As String) As Integer 
    Dim len As Integer 
    Dim fp As FileStream = Nothing 
    Dim marker(1) As Byte 
    Dim data(15) As Byte 
    Dim components As Byte = 0 

    GetJpegBpp = -2 
    Try 
     fp = New FileStream(FileName, FileMode.Open, FileAccess.Read) 
     GetJpegBpp = -1 
     If fp.Read(marker, 0, 2) < 2 OrElse marker(0) <> &HFF OrElse marker(1) <> &HD8 Then Exit Function 
     Do 
      If fp.Read(marker, 0, 2) < 2 OrElse marker(0) <> &HFF OrElse (marker(1) > 1 And marker(1) < &HC0) Then Exit Function 
      If (marker(1) < &HD0 Or marker(1) > &HD9) AndAlso marker(1) > 1 Then 
       If fp.Read(data, 0, 2) < 2 Then Exit Function 
       len = (CInt(data(0)) << 8) Or data(1) 
       len -= 2 
       If len < 0 Then Exit Function 
       If (marker(1) >= &HC0) And (marker(1) <= &HC3) Then 
        If len < 9 OrElse fp.Read(data, 0, 6) < 6 Then Exit Function 
        components = data(5) 
        If components = 0 OrElse components = 2 OrElse components > 4 OrElse (components * 3 + 6) <> len Then Exit Function 
        len -= 6 
       ElseIf marker(1) = &HDA Then 
        If len < (4 + 2 * components) Or (fp.ReadByte() <> components) Then Exit Function 
        len -= 1 
       End If 
       fp.Position += len 
      End If 
     Loop Until marker(1) = &HDA Or marker(1) = &HD9 
     If components = 0 OrElse marker(1) = &HD9 OrElse (fp.Length - fp.Position) < 3 Then Exit Function 
    Catch 
     Exit Function 
    Finally 
     If Not fp Is Nothing Then fp.Close() 
    End Try 
    GetJpegBpp = components * 8 
End Function 

您需要替換該行

iscmyk = ((DirectCast(img.Flags, Imaging.ImageFlags) And Imaging.ImageFlags.ColorSpaceCmyk) = Imaging.ImageFlags.ColorSpaceCmyk) 

與此:

iscmyk = (GetJpegBpp(ofd.FileName) = 32) 

最後,我還沒有測試此代碼與CMYK JPEG圖像,但我想它應該工作...

+0

你的代碼是完美的工作 – Dandy