星期二, 9月 07, 2010

[Silverlight] 將畫面上元件輸出為圖片

VB:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        Dim bitmap As WriteableBitmap = New WriteableBitmap(can, Nothing)

        If Not IsNothing(bitmap) Then
            Dim savedia As SaveFileDialog = New SaveFileDialog()
            savedia.Filter = "JPEG Files (*.jpeg)|*.jpeg"
            savedia.DefaultExt = ".jpeg"

            If savedia.ShowDialog() Then
                Using st As System.IO.Stream = savedia.OpenFile()
                    SaveToFile(bitmap, st)
                    MessageBox.Show("done")
                End Using
            End If
        End If

    End Sub

    Private Shared Sub SaveToFile(ByVal bitmap As WriteableBitmap, ByVal st As System.IO.Stream)
        Dim wid As Integer = bitmap.PixelWidth
        Dim hei As Integer = bitmap.PixelHeight
        Dim bands As Integer = 2
        Dim raster()(,) As Byte = New Byte(bands)(,) {}

        For index = 0 To bands
            raster(index) = New Byte(wid, hei) {}

        Next

        For row = 0 To hei - 1

            For col = 0 To wid - 1
                Dim pixel As Integer = bitmap.Pixels(wid * row + col)
                Dim tmp As Integer

                tmp = (pixel >> 16) Mod 256
                raster(0)(col, row) = (256 + tmp) Mod 256
                tmp = (pixel >> 8) Mod 256
                raster(1)(col, row) = (256 + tmp) Mod 256
                tmp = pixel Mod 256
                raster(2)(col, row) = (256 + tmp) Mod 256

            Next

        Next
        Dim model As ColorModel = New ColorModel() With {.colorspace = ColorSpace.RGB}
        Dim img As FluxJpeg.Core.Image = New FluxJpeg.Core.Image(model, raster)

        Using ms As System.IO.MemoryStream = New System.IO.MemoryStream
            Dim encoder As FluxJpeg.Core.Encoder.JpegEncoder = New FluxJpeg.Core.Encoder.JpegEncoder(img, 100, ms)
            encoder.Encode()
            ms.Seek(0, IO.SeekOrigin.Begin)
            Dim binary() As Byte = New Byte(ms.Length) {}
            Dim byteread = ms.Read(binary, 0, ms.Length)
            st.Write(binary, 0, binary.Length)
        End Using

    End Sub

C#:網路找就有了...差異較大的地方就是轉byte,VB CByte很蠢就是了...
此外要去抓fjCore dll才能使用

沒有留言: