lunes, 12 de abril de 2010

Visualizador de imágenes

Código fuente en visual basic.net 2005 de un visualizador de imágenes

El programa tiene la opción para visualizar en un picturebox la previa de imagen, o al hacer clic en el archivo, visualizarla en otro formulario. También una opción para guardar la imagen seleccionada a otro formato, como bmp, gif, png o jpg

El código fuente para poder cargar en el control Listview los íconos asociados al tipo de archivo y una parte del código para cargar las unidades y carpetas en el control treeview, están sacadas del siguiente enlace

--------------------------------------------------------------------------------

Actualizado
Este es el mismo código fuente para visualizar imágenes pero con algunas modificaciones en el código, ya que el anterior programa , cuando se listaban muchas imágenes en el control ListView, se hacía muy lento y además producía errores.

En esta versión, no se visualiza el tipo de ícono asociado junto al los items del ListView, es decir el Listview se usa sin ImageList, y solamente muestra el nombre del archivo , la fecha y el tipo, pero sin el SmallIcon

También tiene otra opción para listar todas las imágenes de un directorio incluyendo las subcarpetas que contenga, y un pequeño código para realizar la vista previa del gráfico, pero escalandola, y no como estaba en el anterior ejemplo que usaba el sizeMode stretch del control picturebox

--------------------------------------------------------------------------------

Código fuente
( form1 : Un Listview, un treeview, un Statustrip y un PictureBox1 )

Texto planoCopiar código fuenteImprimir
Option Explicit On

'NameSpace para acceder a los directorios y archivos del sistema
Imports System.IO
Imports System.Runtime.InteropServices
'NameSpace para acceder a la clase image
Imports System.Drawing

Public Class Form1
' Array extensiones para los archivos gráficos
Private sExtension() As String = {"*.jpg", "*.bmp", "*.png", _
"*.ico", "*.gif", "*.wmf", _
"*.jpeg", "*.tif", "*.psd"}

' Estrucutura para usar con la función SHGetFileInfo _
' y recuperar el ícono asociado al archivo
Private Structure SHFILEINFO
Public hIcon As IntPtr ' : icon
Public iIcon As Integer ' : icondex
Public dwAttributes As Integer ' : SFGAO_ flags
_
Public szDisplayName As String
_
Public szTypeName As String
End Structure

Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
(ByVal pszPath As String, _
ByVal dwFileAttributes As Integer, _
ByRef psfi As SHFILEINFO, _
ByVal cbFileInfo As Integer, _
ByVal uFlags As Integer) As IntPtr

' Constantes para SHGetFileInfo
Private Const SHGFI_ICON = &H100
Private Const SHGFI_SMALLICON = &H1
Private Const SHGFI_LARGEICON = &H0 ' Large icon
Private Const MAX_PATH = 260

' Cargar los íconos en el imagelist para el Listview
Private Sub cargar_iconos_de_Archivos( _
ByVal sPath As String, _
ByVal ImageList As ImageList)


On Error Resume Next
Dim shInfo As SHFILEINFO
shInfo = New SHFILEINFO()

' buffers
With shInfo
.szDisplayName = New String(vbNullChar, MAX_PATH)
.szTypeName = New String(vbNullChar, 80)
End With
Dim hIcon As IntPtr

' recuperar el handle de la imagen
hIcon = SHGetFileInfo( _
sPath, _
0, _
shInfo, _
Marshal.SizeOf(shInfo), _
SHGFI_ICON Or SHGFI_SMALLICON)

' crear el ícono y agregarlo al ImageList
Dim MyIcon As Drawing.Bitmap
MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap

With ImageList
.Images.Add(sPath.ToString(), MyIcon)
End With

On Error GoTo 0

End Sub

Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

With ListView1
.View = View.Details ' vista detalle
.Columns.Add("Nombre de Archivo ", 150, HorizontalAlignment.Left)
.Columns.Add("Tipo ", 80, HorizontalAlignment.Left)
.Columns.Add("Fecha ", 150, HorizontalAlignment.Left)
' asociar el imagelist para los íconos grandes y chicos
.SmallImageList = ImageList2
.LargeImageList = ImageList2
.GridLines = True
.FullRowSelect = True ' seleccionar fila completa
.MultiSelect = False
End With

' Propiedades del imagelist para el treeview
With ImageList1
.TransparentColor = Color.White
.ColorDepth = ColorDepth.Depth32Bit
End With

' Propiedades del imagelist para el ListView
With ImageList2
'.TransparentColor = Color.White
.ColorDepth = ColorDepth.Depth32Bit
End With

' configurar propiedades del treeview
With TreeView1
' Para subrayar el nodo como hipervínculo
.HotTracking = True
.ShowPlusMinus = False
.ShowRootLines = True
.ShowLines = True
.Tag = ""
.Sort()
End With
' llenar treeview con los drives
Cargar_Drives()
End Sub

' cargar las unidades del sistema en el treeview
Private Sub Cargar_Drives()
Try
' Obtener las unidades con GetDrives
For Each Drive As DriveInfo In System.IO.DriveInfo.GetDrives
' Inicializa el Nodo
Dim Tnode As TreeNode = TreeView1.Nodes.Add(Drive.Name.ToString)
'Cargar el ícono de acuerdo al tipo de drive
Dim n As Integer = 0
Select Case Drive.DriveType
Case DriveType.CDRom
n = 3
Case DriveType.Removable
n = 4
Case DriveType.Network
n = 5
Case Else
n = 0
End Select

With Tnode
.ImageIndex = n
.SelectedImageIndex = n
.Tag = Drive.Name.ToString ' path
End With
Next
' errores
Catch ex As Exception
Debug.Print(ex.Message.ToString)
End Try
End Sub

' buscar archivos y cargarlos en el Listview
Private Sub cargar_listview( _
ByVal sPath As String, _
ByVal lv As ListView, _
Optional ByVal Nivel As FileIO.SearchOption = FileIO.SearchOption.SearchTopLevelOnly)

Dim Extension As String
Dim SubItemIndex As Integer
Dim Fecha As String



If IO.Directory.Exists(sPath) Then
Try
' si el archivo existe

Me.Cursor = Cursors.WaitCursor
' vaciar los controles
ImageList2.Images.Clear()
lv.Items.Clear()

' busca los ficheros en el path ( solo un nivel )
For Each file As String In My.Computer.FileSystem.GetFiles( _
sPath, _
Nivel, _
sExtension)

' crear el ícono y lo carga en la lista de imagenes
cargar_iconos_de_Archivos(file.ToString, ImageList2)
' extensión y fecha de modificación del archivo
Extension = IO.Path.GetExtension(file).ToString
Fecha = IO.File.GetLastWriteTime(file).ToString()

' agregar el elemento
With lv
.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
.Items(SubItemIndex).SubItems.Add(Extension.ToString() & " File")
.Items(SubItemIndex).SubItems.Add(Fecha.ToString())
SubItemIndex += 1
End With
' Application.DoEvents()
Next

' ordenar alfabeticamente
lv.Sort()

Catch ex1 As AccessViolationException
Debug.Print(ex1.Message.ToString)
Catch ex2 As Exception
Debug.Print(ex2.Message.ToString)
Finally
' quitar la imagen del picturebox
PictureBox1.ImageLocation = Nothing
Me.Cursor = Cursors.Default
End Try
End If
End Sub

Private Sub TreeView1_NodeMouseClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _
Handles TreeView1.NodeMouseClick
' si no se está haciendo clic en el mismo nodo ...
If e.Node.Tag.ToString <> TreeView1.Tag.ToString Then
' cargar el nodo
Cargar_treeview(e.Node)
' cargar listado
cargar_listview(e.Node.Tag.ToString, ListView1, FileIO.SearchOption.SearchTopLevelOnly)
End If
' si el nodo no está expandido lo expande
If e.Node.IsExpanded = False Then
e.Node.Expand()
End If
' ruta del nodo actual
TreeView1.Tag = e.Node.Tag.ToString
End Sub

Private Sub Cargar_treeview(ByVal n As TreeNode)
If Not n Is Nothing Then
n.Nodes.Clear()
Dim sPath As String = n.Tag.ToString
' le pasa el nodo donde se está ubicado y _
' el path para cargar ese nodo en el treeview
AddAllFolders(n, sPath)
End If
End Sub

' Obtener los directorios del nodo actual y crear los nodos
Private Sub AddAllFolders( _
ByVal TNode As TreeNode, _
ByVal FolderPath As String)

Try
Me.Cursor = Cursors.WaitCursor
For Each FolderNode As String In Directory.GetDirectories(FolderPath)

'inicializar el nodo
Dim SubFolderNode As TreeNode = TNode.Nodes.Add( _
FolderNode.Substring(FolderNode.LastIndexOf("\"c) + 1))
' tag con el path y establece las imagenes de carpeta
With SubFolderNode
.Tag = FolderNode
.ImageIndex = 1
.SelectedImageIndex = 2
End With
Next
Catch ex As Exception
If Err.Number <> 57 Then
MsgBox(ex.Message.ToString)
End If
Finally
Me.Cursor = Cursors.Default
End Try
End Sub

Private Sub Ver_Imagen(ByVal Spath As String)

Form2.mPath = Spath
Form2.Show()
End Sub

Private Sub SalirToolStripMenuItem_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles SalirToolStripMenuItem.Click
Application.Exit()
End Sub


Private Sub ListView1_KeyPress( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles ListView1.KeyPress
If Not ListView1.FocusedItem Is Nothing Then
If File.Exists(ListView1.FocusedItem.ImageKey.ToString) Then
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End If
End If
End Sub

Private Sub ListView1_MouseClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseClick

If ListView1.FocusedItem Is Nothing Then
Exit Sub
End If

'ImageKey es el path de la imagen
Dim sPathImg As String = ListView1.FocusedItem.ImageKey.ToString
' si el path existe ...
If File.Exists(sPathImg) Then
' mostrar la ruta completa del archivo seleccionado en el statusStrip
StatusStrip1.Items(0).Text = sPathImg.ToString
' cargar la imagen en el picturebox
PictureBox1.ImageLocation = sPathImg.ToString
End If
End Sub
Private Sub ListView1_MouseDoubleClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick
' Abrir la imagen en el otro formulario al hacer dobleClic
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End Sub

Private Sub PictureBox1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles PictureBox1.Click
' Abrir la imagen en el otro formulario al hacer clic en el picturebox1
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End Sub

' guardar el gráfico seleccionado en : png, bmp, gif ...
Private Sub Guardar_Imagen_Como_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click

Dim spathOrigen As String = ""

If Not ListView1.FocusedItem Is Nothing Then
spathOrigen = ListView1.FocusedItem.ImageKey.ToString
Else
MsgBox("No hay imagen seleccionada para guardar", MsgBoxStyle.Critical)
Exit Sub
End If

Dim saveFdlg As New SaveFileDialog

With saveFdlg
'Agregar los filtros de imagen al SaveFileDialog
.Filter = "Archivo Png|*.Png|Archivo Jpg|*.jpg|Archivo Bmp|*.bmp|Archivo Gif|*.gif"
'si se presionó el botón OK
If .ShowDialog() = Windows.Forms.DialogResult.OK Then

Dim imagen As New Bitmap(spathOrigen)
Dim filtro As Imaging.ImageFormat = Nothing

' Establecer el formato de imagen seleccionado ( Png, Jpeg, Bmp y Gif)
Select Case .FilterIndex
Case 1 : filtro = Imaging.ImageFormat.Png
Case 2 : filtro = Imaging.ImageFormat.Jpeg
Case 3 : filtro = Imaging.ImageFormat.Bmp
Case 4 : filtro = Imaging.ImageFormat.Gif
End Select
Try
If Not filtro Is Nothing Then
' guardar la imagen
imagen.Save(.FileName, filtro)
MsgBox("la imagen se guardó en: " & .FileName.ToString, _
MsgBoxStyle.Information)
Else
MsgBox("No se guardó la imagen", MsgBoxStyle.Critical)
End If
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Critical, _
"error al exportar imagen")
End Try

End If
End With
End Sub

Private Sub Buscar_Imagenes_ToolStripMenu_Item_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BuscarImagenesToolStripMenuItem.Click
MsgBox("Falta código", MsgBoxStyle.Information)
End Sub

Private Sub imprimir_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click
MsgBox("Falta código", MsgBoxStyle.Information)
End Sub

' Ordenar items al hacer clic en el encabezado de columna del ListView
Private Sub ListView1_ColumnClick(ByVal sender As Object, _
ByVal e As System.Windows.Forms.ColumnClickEventArgs) _
Handles ListView1.ColumnClick
If e.Column <> 0 Then Exit Sub
If ListView1.Sorting = SortOrder.Ascending Then
ListView1.Sorting = SortOrder.Descending
Else
ListView1.Sorting = SortOrder.Ascending
End If
ListView1.Sort()
End Sub
End Class
Option Explicit On

'NameSpace para acceder a los directorios y archivos del sistema
Imports System.IO
Imports System.Runtime.InteropServices
'NameSpace para acceder a la clase image
Imports System.Drawing

Public Class Form1
' Array extensiones para los archivos gráficos
Private sExtension() As String = {"*.jpg", "*.bmp", "*.png", _
"*.ico", "*.gif", "*.wmf", _
"*.jpeg", "*.tif", "*.psd"}

' Estrucutura para usar con la función SHGetFileInfo _
' y recuperar el ícono asociado al archivo
Private Structure SHFILEINFO
Public hIcon As IntPtr ' : icon
Public iIcon As Integer ' : icondex
Public dwAttributes As Integer ' : SFGAO_ flags
_
Public szDisplayName As String
_
Public szTypeName As String
End Structure

Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
(ByVal pszPath As String, _
ByVal dwFileAttributes As Integer, _
ByRef psfi As SHFILEINFO, _
ByVal cbFileInfo As Integer, _
ByVal uFlags As Integer) As IntPtr

' Constantes para SHGetFileInfo
Private Const SHGFI_ICON = &H100
Private Const SHGFI_SMALLICON = &H1
Private Const SHGFI_LARGEICON = &H0 ' Large icon
Private Const MAX_PATH = 260

' Cargar los íconos en el imagelist para el Listview
Private Sub cargar_iconos_de_Archivos( _
ByVal sPath As String, _
ByVal ImageList As ImageList)


On Error Resume Next
Dim shInfo As SHFILEINFO
shInfo = New SHFILEINFO()

' buffers
With shInfo
.szDisplayName = New String(vbNullChar, MAX_PATH)
.szTypeName = New String(vbNullChar, 80)
End With
Dim hIcon As IntPtr

' recuperar el handle de la imagen
hIcon = SHGetFileInfo( _
sPath, _
0, _
shInfo, _
Marshal.SizeOf(shInfo), _
SHGFI_ICON Or SHGFI_SMALLICON)

' crear el ícono y agregarlo al ImageList
Dim MyIcon As Drawing.Bitmap
MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap

With ImageList
.Images.Add(sPath.ToString(), MyIcon)
End With

On Error GoTo 0

End Sub

Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load

With ListView1
.View = View.Details ' vista detalle
.Columns.Add("Nombre de Archivo ", 150, HorizontalAlignment.Left)
.Columns.Add("Tipo ", 80, HorizontalAlignment.Left)
.Columns.Add("Fecha ", 150, HorizontalAlignment.Left)
' asociar el imagelist para los íconos grandes y chicos
.SmallImageList = ImageList2
.LargeImageList = ImageList2
.GridLines = True
.FullRowSelect = True ' seleccionar fila completa
.MultiSelect = False
End With

' Propiedades del imagelist para el treeview
With ImageList1
.TransparentColor = Color.White
.ColorDepth = ColorDepth.Depth32Bit
End With

' Propiedades del imagelist para el ListView
With ImageList2
'.TransparentColor = Color.White
.ColorDepth = ColorDepth.Depth32Bit
End With

' configurar propiedades del treeview
With TreeView1
' Para subrayar el nodo como hipervínculo
.HotTracking = True
.ShowPlusMinus = False
.ShowRootLines = True
.ShowLines = True
.Tag = ""
.Sort()
End With
' llenar treeview con los drives
Cargar_Drives()
End Sub

' cargar las unidades del sistema en el treeview
Private Sub Cargar_Drives()
Try
' Obtener las unidades con GetDrives
For Each Drive As DriveInfo In System.IO.DriveInfo.GetDrives
' Inicializa el Nodo
Dim Tnode As TreeNode = TreeView1.Nodes.Add(Drive.Name.ToString)
'Cargar el ícono de acuerdo al tipo de drive
Dim n As Integer = 0
Select Case Drive.DriveType
Case DriveType.CDRom
n = 3
Case DriveType.Removable
n = 4
Case DriveType.Network
n = 5
Case Else
n = 0
End Select

With Tnode
.ImageIndex = n
.SelectedImageIndex = n
.Tag = Drive.Name.ToString ' path
End With
Next
' errores
Catch ex As Exception
Debug.Print(ex.Message.ToString)
End Try
End Sub

' buscar archivos y cargarlos en el Listview
Private Sub cargar_listview( _
ByVal sPath As String, _
ByVal lv As ListView, _
Optional ByVal Nivel As FileIO.SearchOption = FileIO.SearchOption.SearchTopLevelOnly)

Dim Extension As String
Dim SubItemIndex As Integer
Dim Fecha As String



If IO.Directory.Exists(sPath) Then
Try
' si el archivo existe

Me.Cursor = Cursors.WaitCursor
' vaciar los controles
ImageList2.Images.Clear()
lv.Items.Clear()

' busca los ficheros en el path ( solo un nivel )
For Each file As String In My.Computer.FileSystem.GetFiles( _
sPath, _
Nivel, _
sExtension)

' crear el ícono y lo carga en la lista de imagenes
cargar_iconos_de_Archivos(file.ToString, ImageList2)
' extensión y fecha de modificación del archivo
Extension = IO.Path.GetExtension(file).ToString
Fecha = IO.File.GetLastWriteTime(file).ToString()

' agregar el elemento
With lv
.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
.Items(SubItemIndex).SubItems.Add(Extension.ToString() & " File")
.Items(SubItemIndex).SubItems.Add(Fecha.ToString())
SubItemIndex += 1
End With
' Application.DoEvents()
Next

' ordenar alfabeticamente
lv.Sort()

Catch ex1 As AccessViolationException
Debug.Print(ex1.Message.ToString)
Catch ex2 As Exception
Debug.Print(ex2.Message.ToString)
Finally
' quitar la imagen del picturebox
PictureBox1.ImageLocation = Nothing
Me.Cursor = Cursors.Default
End Try
End If
End Sub

Private Sub TreeView1_NodeMouseClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _
Handles TreeView1.NodeMouseClick
' si no se está haciendo clic en el mismo nodo ...
If e.Node.Tag.ToString <> TreeView1.Tag.ToString Then
' cargar el nodo
Cargar_treeview(e.Node)
' cargar listado
cargar_listview(e.Node.Tag.ToString, ListView1, FileIO.SearchOption.SearchTopLevelOnly)
End If
' si el nodo no está expandido lo expande
If e.Node.IsExpanded = False Then
e.Node.Expand()
End If
' ruta del nodo actual
TreeView1.Tag = e.Node.Tag.ToString
End Sub

Private Sub Cargar_treeview(ByVal n As TreeNode)
If Not n Is Nothing Then
n.Nodes.Clear()
Dim sPath As String = n.Tag.ToString
' le pasa el nodo donde se está ubicado y _
' el path para cargar ese nodo en el treeview
AddAllFolders(n, sPath)
End If
End Sub

' Obtener los directorios del nodo actual y crear los nodos
Private Sub AddAllFolders( _
ByVal TNode As TreeNode, _
ByVal FolderPath As String)

Try
Me.Cursor = Cursors.WaitCursor
For Each FolderNode As String In Directory.GetDirectories(FolderPath)

'inicializar el nodo
Dim SubFolderNode As TreeNode = TNode.Nodes.Add( _
FolderNode.Substring(FolderNode.LastIndexOf("\"c) + 1))
' tag con el path y establece las imagenes de carpeta
With SubFolderNode
.Tag = FolderNode
.ImageIndex = 1
.SelectedImageIndex = 2
End With
Next
Catch ex As Exception
If Err.Number <> 57 Then
MsgBox(ex.Message.ToString)
End If
Finally
Me.Cursor = Cursors.Default
End Try
End Sub

Private Sub Ver_Imagen(ByVal Spath As String)

Form2.mPath = Spath
Form2.Show()
End Sub

Private Sub SalirToolStripMenuItem_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles SalirToolStripMenuItem.Click
Application.Exit()
End Sub


Private Sub ListView1_KeyPress( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles ListView1.KeyPress
If Not ListView1.FocusedItem Is Nothing Then
If File.Exists(ListView1.FocusedItem.ImageKey.ToString) Then
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End If
End If
End Sub

Private Sub ListView1_MouseClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseClick

If ListView1.FocusedItem Is Nothing Then
Exit Sub
End If

'ImageKey es el path de la imagen
Dim sPathImg As String = ListView1.FocusedItem.ImageKey.ToString
' si el path existe ...
If File.Exists(sPathImg) Then
' mostrar la ruta completa del archivo seleccionado en el statusStrip
StatusStrip1.Items(0).Text = sPathImg.ToString
' cargar la imagen en el picturebox
PictureBox1.ImageLocation = sPathImg.ToString
End If
End Sub
Private Sub ListView1_MouseDoubleClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick
' Abrir la imagen en el otro formulario al hacer dobleClic
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End Sub

Private Sub PictureBox1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles PictureBox1.Click
' Abrir la imagen en el otro formulario al hacer clic en el picturebox1
Ver_Imagen(ListView1.FocusedItem.ImageKey.ToString)
End Sub

' guardar el gráfico seleccionado en : png, bmp, gif ...
Private Sub Guardar_Imagen_Como_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click

Dim spathOrigen As String = ""

If Not ListView1.FocusedItem Is Nothing Then
spathOrigen = ListView1.FocusedItem.ImageKey.ToString
Else
MsgBox("No hay imagen seleccionada para guardar", MsgBoxStyle.Critical)
Exit Sub
End If

Dim saveFdlg As New SaveFileDialog

With saveFdlg
'Agregar los filtros de imagen al SaveFileDialog
.Filter = "Archivo Png|*.Png|Archivo Jpg|*.jpg|Archivo Bmp|*.bmp|Archivo Gif|*.gif"
'si se presionó el botón OK
If .ShowDialog() = Windows.Forms.DialogResult.OK Then

Dim imagen As New Bitmap(spathOrigen)
Dim filtro As Imaging.ImageFormat = Nothing

' Establecer el formato de imagen seleccionado ( Png, Jpeg, Bmp y Gif)
Select Case .FilterIndex
Case 1 : filtro = Imaging.ImageFormat.Png
Case 2 : filtro = Imaging.ImageFormat.Jpeg
Case 3 : filtro = Imaging.ImageFormat.Bmp
Case 4 : filtro = Imaging.ImageFormat.Gif
End Select
Try
If Not filtro Is Nothing Then
' guardar la imagen
imagen.Save(.FileName, filtro)
MsgBox("la imagen se guardó en: " & .FileName.ToString, _
MsgBoxStyle.Information)
Else
MsgBox("No se guardó la imagen", MsgBoxStyle.Critical)
End If
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Critical, _
"error al exportar imagen")
End Try

End If
End With
End Sub

Private Sub Buscar_Imagenes_ToolStripMenu_Item_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles BuscarImagenesToolStripMenuItem.Click
MsgBox("Falta código", MsgBoxStyle.Information)
End Sub

Private Sub imprimir_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click
MsgBox("Falta código", MsgBoxStyle.Information)
End Sub

' Ordenar items al hacer clic en el encabezado de columna del ListView
Private Sub ListView1_ColumnClick(ByVal sender As Object, _
ByVal e As System.Windows.Forms.ColumnClickEventArgs) _
Handles ListView1.ColumnClick
If e.Column <> 0 Then Exit Sub
If ListView1.Sorting = SortOrder.Ascending Then
ListView1.Sorting = SortOrder.Descending
Else
ListView1.Sorting = SortOrder.Ascending
End If
ListView1.Sort()
End Sub
End Class



Código fuente del form2 ( Un Picturebox)

Texto planoCopiar código fuenteImprimir
Option Explicit On


Public Class Form2
' variables
''' '''''''''''''''''''''''''''''''''''''''''
Public mPath As String = ""
Public mEscalaActual As Double

' Aumentar o reducir la imagen
''' ''''''''''''''''''''''''''''''''''''''

Private Sub zoom(ByVal Picbox As PictureBox, ByVal Escala As Single)

With Picbox
' modo de ajuste en zoom
.SizeMode = PictureBoxSizeMode.Zoom

Dim ancho As Integer = .Image.Width
Dim alto As Integer = .Image.Height

' Comprobar si la nueva dimensión no es menor a 16 pixeles
If (ancho * Escala) > 16 And (alto * Escala) > 16 Then
' Establecer nuevo ancho y alto
.Width = ancho * Escala
.Height = alto * Escala

Centrar_Picturebox()

mEscalaActual = Escala

End If
End With
End Sub
' descargar form
Private Sub Form2_FormClosed( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosedEventArgs) _
Handles Me.FormClosed

Me.Hide()
Me.Dispose()

End Sub
' Opciones de evento de tecla del formulario
Private Sub Form2_KeyDown( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles Me.KeyDown

Select Case e.KeyCode
' tecla escape
Case Keys.Escape
Me.Close()
' tecla +
Case Keys.Add
zoom(PictureBox1, mEscalaActual + 0.1)
' tecla -
Case Keys.Subtract
zoom(PictureBox1, mEscalaActual - 0.1)
Case Keys.Enter
Me.Close()
' mover a la siguiente imagen
Case Keys.Right
Static i As Integer = 0
With Form1.ListView1
If i = .Items.Count - 1 Then
i = 0
Else
i = i + 1
End If
.Items(i).Selected = True
iniciar(.Items(i).ImageKey.ToString)
End With
End Select

End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Me.BackColor = Color.Black
' form sin borde ni title bar
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
PictureBox1.BackColor = Color.Black
iniciar(mPath.ToString)

End Sub
' cargar la imagen al iniciar
Private Sub iniciar(ByVal sRuta As String)
Try
With PictureBox1
mEscalaActual = 1
If System.IO.File.Exists(sRuta) Then
.Cursor = Cursors.Hand
.SizeMode = PictureBoxSizeMode.AutoSize
' leer la imagen con FromFile
.Image = Image.FromFile(sRuta)
' centrar en el formulario
Centrar_Picturebox()
Else
Me.Close()
End If
End With
Catch ex As OutOfMemoryException
Me.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
' descargar al hacer dobleclic en el formulario
Private Sub Form2_MouseDoubleClick( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDoubleClick
Me.Close()
End Sub


Private Sub Centrar_Picturebox()
With PictureBox1
.Top = (Me.Height - .Height) \ 2
.Left = (Me.Width - .Width) \ 2
End With
End Sub

Private Sub PictureBox1_MouseDown1( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles PictureBox1.MouseDown

Select Case e.Button
' Aumentar con el botón izquierdo
Case Windows.Forms.MouseButtons.Left
zoom(PictureBox1, mEscalaActual + 0.2)
' Reducir con el botón derecho
Case Windows.Forms.MouseButtons.Right
zoom(PictureBox1, mEscalaActual - 0.2)
End Select
End Sub
End Class

No hay comentarios:

Publicar un comentario