Extrahování ikon z *.ico souboru
Přidáno: 6.8.2008
Kategorie: VB.NET - Soubory
Autor: Jan Novák
V tomto snippetu bych rád předvedl, jak lze jednoduše a rychle extrahovat ikony z *.ico souborů.
Článek je částečně založen na http://www.codeproject.com/KB/vb/MultiIcon.aspx .
Specifikaci *.ico formátu naleznete na http://www.daubnet.com/formats/ICO.html .
UPOZORNĚNÍ: Tento kód Vám neumožní extrahovat Vista ikony (255x255). Pokud takovou možnost hledáte, může pomoct tento článek: http://www.codeproject.com/KB/cs/IconLib.aspx
Imports System
Imports System.IO
Imports System.Collections.Generic
Public Class MultiIcon
Shared stream As MemoryStream
Private items As New List(Of Icon)
Private Class Header
Public Reserved As Short
Public Type As Short
Public Count As Short
Public Sub New()
Dim br As New BinaryReader(stream)
Me.Reserved = br.ReadInt16
Me.Type = br.ReadInt16
Me.Count = br.ReadInt16
End Sub
End Class
Private Class Entry
Public Width As Byte
Public Height As Byte
Public Colors As Byte
Public Reserved As Byte
Public Planes As Short
Public BitsPerPixel As Short
Public Length As Integer
Public Offset As Integer
Public Sub New()
Dim br As New BinaryReader(stream)
Me.Width = br.ReadByte
Me.Height = br.ReadByte
Me.Colors = br.ReadByte
Me.Reserved = br.ReadByte
Me.Planes = br.ReadInt16
Me.BitsPerPixel = br.ReadInt16
Me.Length = br.ReadInt32
Me.Offset = br.ReadInt32
End Sub
End Class
Public Sub New(ByVal path As String)
Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
Dim bytes(fs.Length) As Byte
fs.Read(bytes, 0, fs.Length)
stream = New MemoryStream(bytes)
stream.Seek(0, SeekOrigin.Begin)
End Using
Dim header As Header = New Header
Dim entries As New List(Of Entry)
For i As Integer = 0 To header.Count - 1
entries.Add(New Entry())
Next
For i As Integer = 0 To header.Count - 1
Dim entry As Entry = entries(i)
Dim bytes(entry.Length) As Byte
Using ms As New MemoryStream
Using bw As New BinaryWriter(ms)
stream.Seek(entry.Offset, SeekOrigin.Begin)
stream.Read(bytes, 0, entry.Length)
With bw
Dim count As Short = 1
Dim offset As Integer = 22
.Write(header.Reserved)
.Write(header.Type)
.Write(count)
.Write(entry.Width)
.Write(entry.Height)
.Write(entry.Colors)
.Write(entry.Reserved)
.Write(entry.Planes)
.Write(entry.BitsPerPixel)
.Write(entry.Length)
.Write(offset)
.Write(bytes)
End With
ms.Seek(0, SeekOrigin.Begin)
items.Add(New Icon(ms, entry.Width, entry.Height))
End Using
End Using
Next
stream.Close()
End Sub
Public ReadOnly Property Count() As Integer
Get
Return items.Count
End Get
End Property
Public ReadOnly Property Item(ByVal index As Integer) As Icon
Get
Return items.Item(index)
End Get
End Property
End Class