Introduction
In TV-broadcasting and game development, the Truevision Targa Format is very popular. The .NET Framework does not support this format. This class does save a given GDI+ bitmap to the 32-Bit version of the Targa-Format.
Background
Information about the Truevision Targa format can be found here.
Using the Code
The class exports the shared sub SaveAsTarga. It has two arguments, Filename and Picture. Filename is the name under which the file is saved. Picture is a GDI+ Bitmap with PixelFormat.Format32bppArgb that shall be saved.
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Public Class TargaFile
Public Shared Sub SaveAsTarga(Filename As String, Picture As Bitmap)
If Picture.PixelFormat <> Imaging.PixelFormat.Format32bppArgb Then
Throw New Exception("Must be as 32-Bit Image")
Exit Sub
End If
If Not IO.Directory.Exists(IO.Path.GetDirectoryName(Filename)) Then
Throw New Exception("Path to save file does not exist")
Exit Sub
End If
Picture.RotateFlip(RotateFlipType.RotateNoneFlipY)
Using FS As New FileStream(Filename, FileMode.Create, FileAccess.Write)
Dim bw As BinaryWriter = New BinaryWriter(FS)
Dim sh As Int16 = 0
bw.Write(CByte(0)) bw.Write(CByte(0)) bw.Write(CByte(2))
bw.Write(sh) bw.Write(sh) bw.Write(CByte(0))
bw.Write(sh) bw.Write(sh)
sh = Picture.Width
bw.Write(sh) sh = Picture.Height
bw.Write(sh)
bw.Write(CByte(32)) bw.Write(CByte(8))
Dim bmpData As BitmapData = Picture.LockBits(New Rectangle_
(0, 0, Picture.Width, Picture.Height), _
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Dim ptr As IntPtr = bmpData.Scan0
Dim bytes As Integer = bmpData.Stride * Picture.Height
Dim rgbValues(bytes - 1) As Byte
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
bw.Write(rgbValues)
Picture.UnlockBits(bmpData)
Dim ln As Int32 = 0
bw.Write(ln)
bw.Write(ln)
bw.Write("TRUEVISION-XFILE.")
bw.Write(CByte(0))
bw.Flush()
FS.Flush()
bw.Close()
FS.Close()
End Using
End Sub
End Class
History