begin process at 2010 02 10 05:36:09
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Graphique

 > GETPIXEL TRÈS RAPIDE

GETPIXEL TRÈS RAPIDE


 Information sur la source

Note :
9 / 10 - par 1 personne
9,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Graphique Source .NET ( DotNet ) Classé sous :bitmap, getpixel, setpixel Niveau :Débutant Date de création :19/04/2006 Date de mise à jour :03/01/2008 20:47:14 Vu / téléchargé :11 210 / 869

Auteur : ShadowTzu

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (17)
Ajouter un commentaire et/ou une note


 Description

cette classe vous permet de prendre/écrire un pîxel sur une image beaucoup plus rapidement que la classe Bitmap du framework

Source

  • Imports System.Drawing
  • Imports System.Drawing.Imaging
  • Public Class BitmapFast
  • #Region "private"
  • Private b() As Byte
  • Private i_Width As Integer
  • Private i_Height As Integer
  • Private i_Stride As Integer
  • Private i_ColorSize As Integer
  • #End Region
  • #Region "public"
  • Public Disposed As Boolean
  • #End Region
  • #Region "New"
  • Public Sub New(ByVal filename As String)
  • If (filename = "") Or (System.IO.File.Exists(filename) = False) Then
  • MsgBox("file '" & filename & "' not found!")
  • Exit Sub
  • End If
  • Dim pv_bitmap As Bitmap = Nothing
  • pv_bitmap = New Bitmap(filename)
  • i_Width = pv_bitmap.Width
  • i_Height = pv_bitmap.Height
  • Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
  • Dim bitmapData As BitmapData = pv_bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)
  • i_stride = bitmapData.Stride
  • i_ColorSize = bitmapData.Stride / bitmapData.Width
  • ReDim b(bitmapData.Height * i_stride)
  • System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, b, 0, b.Length - 1)
  • pv_bitmap.UnlockBits(bitmapData)
  • pv_bitmap.Dispose()
  • pv_bitmap = Nothing
  • End Sub
  • #End Region
  • #Region "Function"
  • Public Function Getpixel(ByVal x As Integer, ByVal y As Integer) As Color
  • Dim red, green, blue As Byte
  • red = b(x * i_ColorSize + y * i_Stride)
  • green = b((x * i_ColorSize + 1) + y * i_Stride)
  • blue = b((x * i_ColorSize + 2) + y * i_Stride)
  • Return Color.FromArgb(255, red, green, blue)
  • End Function
  • Public Sub Setpixel(ByVal x As Integer, ByVal y As Integer, ByVal color As Color)
  • b(x * i_ColorSize + y * i_Stride) = color.R
  • b((x * i_ColorSize + 1) + y * i_Stride) = color.G
  • b((x * i_ColorSize + 2) + y * i_Stride) = color.B
  • End Sub
  • #End Region
  • #Region "Save"
  • Public Sub Save(ByVal filename As String, ByVal myFormat As ImageFormat)
  • Dim pv_bitmap As Bitmap = Nothing
  • pv_bitmap = New Bitmap(i_Width, i_Height, PixelFormat.Format24bppRgb)
  • Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
  • Dim bitmapData As Imaging.BitmapData = pv_bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)
  • System.Runtime.InteropServices.Marshal.Copy(b, 0, bitmapData.Scan0, b.Length - 1)
  • pv_bitmap.Save(filename, myFormat)
  • pv_bitmap.UnlockBits(bitmapData)
  • pv_bitmap.Dispose()
  • pv_bitmap = Nothing
  • End Sub
  • #End Region
  • #Region "GetBitmap"
  • Public Function Get_Bitmap() As Bitmap
  • Get_Bitmap = New Bitmap(i_Width, i_Height, PixelFormat.Format24bppRgb)
  • Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
  • Dim bitmapData As Imaging.BitmapData = Get_Bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)
  • bitmapData.Stride = CInt(bitmapData.Stride / i_Width) * i_Width
  • System.Runtime.InteropServices.Marshal.Copy(b, 0, bitmapData.Scan0, b.Length - 1)
  • Get_Bitmap.UnlockBits(bitmapData)
  • End Function
  • #End Region
  • #Region "property"
  • Public ReadOnly Property Width() As Integer
  • Get
  • Return i_Width
  • End Get
  • End Property
  • Public ReadOnly Property Height() As Integer
  • Get
  • Return i_Height
  • End Get
  • End Property
  • #End Region
  • #Region "dispose"
  • Public Sub Dispose()
  • If Disposed = True Then Exit Sub
  • Erase b
  • Disposed = True
  • End Sub
  • Protected Overrides Sub Finalize()
  • MyBase.Finalize()
  • If Disposed = False Then Dispose()
  • End Sub
  • #End Region
  • End Class
Imports System.Drawing
Imports System.Drawing.Imaging
Public Class BitmapFast

#Region "private"
    Private b() As Byte
    Private i_Width As Integer
    Private i_Height As Integer    
    Private i_Stride As Integer
    Private i_ColorSize As Integer
#End Region

#Region "public"
    Public Disposed As Boolean
#End Region

#Region "New"
    Public Sub New(ByVal filename As String)
        If (filename = "") Or (System.IO.File.Exists(filename) = False) Then
            MsgBox("file '" & filename & "' not found!")
            Exit Sub
        End If

        Dim pv_bitmap As Bitmap = Nothing
        pv_bitmap = New Bitmap(filename)
        i_Width = pv_bitmap.Width
        i_Height = pv_bitmap.Height

        Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
        Dim bitmapData As BitmapData = pv_bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)        
        i_stride = bitmapData.Stride
        i_ColorSize = bitmapData.Stride / bitmapData.Width
        ReDim b(bitmapData.Height * i_stride)
        System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, b, 0, b.Length - 1)
        pv_bitmap.UnlockBits(bitmapData)

        pv_bitmap.Dispose()
        pv_bitmap = Nothing
    End Sub
#End Region

#Region "Function"
    Public Function Getpixel(ByVal x As Integer, ByVal y As Integer) As Color

        Dim red, green, blue As Byte        
        red = b(x * i_ColorSize + y * i_Stride)
        green = b((x * i_ColorSize + 1) + y * i_Stride)
        blue = b((x * i_ColorSize + 2) + y * i_Stride)

        Return Color.FromArgb(255, red, green, blue)
    End Function

    Public Sub Setpixel(ByVal x As Integer, ByVal y As Integer, ByVal color As Color)        
        b(x * i_ColorSize + y * i_Stride) = color.R
        b((x * i_ColorSize + 1) + y * i_Stride) = color.G
        b((x * i_ColorSize + 2) + y * i_Stride) = color.B
    End Sub
#End Region

#Region "Save"
    Public Sub Save(ByVal filename As String, ByVal myFormat As ImageFormat)
        Dim pv_bitmap As Bitmap = Nothing
        pv_bitmap = New Bitmap(i_Width, i_Height, PixelFormat.Format24bppRgb)

        Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
        Dim bitmapData As Imaging.BitmapData = pv_bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)

        System.Runtime.InteropServices.Marshal.Copy(b, 0, bitmapData.Scan0, b.Length - 1)
        pv_bitmap.Save(filename, myFormat)
        pv_bitmap.UnlockBits(bitmapData)

        pv_bitmap.Dispose()
        pv_bitmap = Nothing

    End Sub

#End Region

#Region "GetBitmap"
    Public Function Get_Bitmap() As Bitmap

        Get_Bitmap = New Bitmap(i_Width, i_Height, PixelFormat.Format24bppRgb)

        Dim bounds As Rectangle = New Rectangle(0, 0, i_Width, i_Height)
        Dim bitmapData As Imaging.BitmapData = Get_Bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb)
        bitmapData.Stride = CInt(bitmapData.Stride / i_Width) * i_Width
        System.Runtime.InteropServices.Marshal.Copy(b, 0, bitmapData.Scan0, b.Length - 1)
        Get_Bitmap.UnlockBits(bitmapData)

    End Function
#End Region

#Region "property"
    Public ReadOnly Property Width() As Integer
        Get
            Return i_Width
        End Get
    End Property

    Public ReadOnly Property Height() As Integer
        Get
            Return i_Height
        End Get
    End Property
#End Region

#Region "dispose"
    Public Sub Dispose()
        If Disposed = True Then Exit Sub
        Erase b
        Disposed = True
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        If Disposed = False Then Dispose()
    End Sub
#End Region

End Class


 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

20 avril 2006 10:36:14 :
correction de la fonction setpixel
20 avril 2006 16:52:44 :
Ajout de la fonction Get_Bitmap
24 avril 2007 21:01:58 :
correction d'un petit bug.
03 janvier 2008 14:55:15 :
Correction du décalage des pixels.
03 janvier 2008 20:47:14 :
Correction de l'inversion du rouge et bleu.

 Sources du même auteur

Source avec Zip Source .NET (Dotnet) ARCHIVER PLUSIEURS FICHIER DANS UN SEUL
Source avec Zip Source avec une capture Source .NET (Dotnet) NORMAL MAPPING
Source avec Zip Source avec une capture Source .NET (Dotnet) TERRAIN 3D AVEC COLLISION

 Sources de la même categorie

Source avec Zip ALBUM PHOTOS par ayoube2009
Source avec Zip Source avec une capture EDITEUR D'AUTOMATES CELLULAIRES par PADYVEN
Source avec Zip Source avec une capture PROGRAMME DE DESSIN À LA SOURIS AVEC OUVERTURE ET ENREGISTRE... par SnkVrt
Source avec Zip Source avec une capture Source .NET (Dotnet) PHOTOSEXPRESS - TRAITEMENT DE PHOTOS par zozo14
Source avec Zip Source avec une capture ÉCRIRE SUR LE WALLPAPER par Rafale71

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) DÉCOUPEUR DE SPRITES (POUR JEUX RPG) par guyom38
Source avec Zip Source avec une capture MENU POPUP AVEC IMAGE par zork74
Source avec Zip Source avec une capture OPÉRATIONS SUR UNE LISTE D'IMAGES par antho2005
Source avec Zip Source avec une capture DÉFORMER UNE IMAGE, FAIRE DES VAGUES (SIN) (UPDATED) par max12
Source avec Zip Source avec une capture COMPARER 2 IMAGES par max12

Commentaires et avis

Commentaire de Pym Corp le 19/04/2006 17:27:21

Tu peux faire des tests de vitesse et obtenir un résultat "parlant" ?
Ca me parait bizarre que ca soit "beaucoup plus rapide" merci :)

Commentaire de ShadowTzu le 19/04/2006 20:12:57

il te suffit de télécharger le zip et de lancer le projet.
Tu y verras la difference de temps entre les 2 methodes getpixel en millisecondes.

Commentaire de Renfield le 20/04/2006 09:27:56 administrateur CS

je suis surtout étonné de voir de telles différences dans les formules de calcul des coordonnées :

         red = b((x * 3) + y * (i_Width * 3))
         green = b((x * 3 + 1) + y * (i_Width * 3))
         blue = b((x * 3 + 2) + y * (i_Width * 3))
  
         b(x + y * Width) = red
         b((x + 1) + (y + 1) * Width) = green
         b((x + 2) + (y + 2) * Width) = blue

pourquoi avoir laissé de telles disparités ?

Commentaire de ShadowTzu le 20/04/2006 10:31:35

oula! t'as raison je corrige ça tout de suite!

Commentaire de Afyn le 20/04/2006 13:26:02

On peut appliquer ça au background d'un contrôle ?

Afyn
Navedac

Commentaire de ShadowTzu le 20/04/2006 16:50:11

oui c'est possible, je met à jour la source en ajoutant un picturebox.

Commentaire de archimed111 le 20/04/2006 16:54:51

Non on peux pas c'est juste pour les pixels d'une image.

J'avais deja utilisé ca moi aussi pour modifier les pixels d'une image  1 à 1 pour par exemple changer les couleurs d'une image.
En fait c'est beaucoup plus rapide on utilise des pointeurs, c'est un peux comme du code unsafe en c#.
Pour donner un chiffre avec le code que j'avais fait sur une grande image a modifié ca donnait :
- pixel par pixel : 12 seconde
- code non managé : 0.56 seconde
- en utilisant les colormatrix : 0.65 seconde.

Commentaire de Afyn le 20/04/2006 21:01:04

Bravo pour le picture box ...

Merci

Afyn
Navedac

Commentaire de Pym Corp le 20/04/2006 23:50:06

Par contre dommage que ca ne soit pas plus commenté que ça, y'a des trucs que je connais pas du tout dans BitmapFast perso

Commentaire de Chrysostome le 29/04/2006 16:30:12

Salut à tous!
Comme je ne sais pas où poser ma question, et que les lecteurs d'içi me semblent avertis:
Comment procéderiez-vous pour récupérer par scan, les réponses d'une fiche avec cases à cocher?
Merci de vos réponses.

Commentaire de laurent_psy le 02/08/2006 06:47:53

dans vc++, en utilisant un simple array<Byte> a une dimesion on peut changer toutes les couleurs de l image en environ 15ms pas plus. meme 0.56s je trouve ca enorme. imaginez que votre video camera numerique mette ce temps la sur chaque trame, pas tres fluide non? 2fps

Commentaire de laurent_psy le 02/08/2006 06:49:17

ce que je veux dire c est que pour la rapidite il faut oublier les methodes genre "getpixel" que l on doit appeler pour chaque pixel. sur ce a+

Commentaire de MoiDebutantVB le 23/04/2007 18:44:36

Au niveau de cette ligne :
        System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, b, 0, pv_bitmap.Width * bitmapData.Stride)
j'obtiens une erreur :
L'exception System.AccessViolationException n'a pas été gérée
  Message="Tentative de lecture ou d'écriture de mémoire protégée. Cela indique souvent qu'une autre mémoire est endommagée."
  Source="mscorlib"
  StackTrace:
       à System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr source, Object destination, Int32 startIndex, Int32 length)
       à System.Runtime.InteropServices.Marshal.Copy(IntPtr source, Byte[] destination, Int32 startIndex, Int32 length)
       à Background_Transformer.BitmapFast..ctor(String filename) dans D:\Documents\Clément\Programmes\VB\Visual Studio\Background transformer\Application\BitmapFast.vb:ligne 30
       à Background_Transformer.MainForm.StartClick(Object sender, EventArgs e) dans D:\Documents\Clément\Programmes\VB\Visual Studio\Background transformer\Application\MainForm.vb:ligne 545
       à System.Windows.Forms.Control.OnClick(EventArgs e)
       à System.Windows.Forms.Button.OnClick(EventArgs e)
       à System.Windows.Forms.Button.WndProc(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       à System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       à System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       à System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       à System.Windows.Forms.Control.WmCommand(Message& m)
       à System.Windows.Forms.Control.WndProc(Message& m)
       à System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       à System.Windows.Forms.ContainerControl.WndProc(Message& m)
       à System.Windows.Forms.Form.WndProc(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       à System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       à System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       à System.Windows.Forms.Control.DefWndProc(Message& m)
       à System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       à System.Windows.Forms.Control.WndProc(Message& m)
       à System.Windows.Forms.ButtonBase.WndProc(Message& m)
       à System.Windows.Forms.Button.WndProc(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       à System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       à System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       à System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       à System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       à System.Windows.Forms.Application.Run(Form mainForm)
       à Background_Transformer.MainForm.Main() dans D:\Documents\Clément\Programmes\VB\Visual Studio\Background transformer\Application\MainForm.vb:ligne 50
       à System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       à System.Threading.ThreadHelper.ThreadStart()

Quelqu'un à t'il déjà eu cette erreur ?
Ou qqun sait-il comment la résoudre ?

Quoi qu'il en soit,
Merci beaucoup,
CFP

Commentaire de ShadowTzu le 23/04/2007 20:04:44

il est possible que j'ai fait une petite erreur avec "pv_bitmap.Width * bitmapData.Stride", remplace par ça dans Sub New:

'[...]
ReDim b(bitmapData.Height * bitmapData.Stride)
System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, b, 0, b.Length - 1)
'[...]

tiens moi au courant ;)

Commentaire de MoiDebutantVB le 24/04/2007 18:23:49

Ok, ca marche.
9/10.

Commentaire de lukebalthazar le 02/01/2008 19:06:39

C'est juste parfait!
mais....
certaines images, et je ne comprends pas pourquoi "certaines", se trouvent decalées lors du setpixel.
je fais :

Color_S = map1.Getpixel(i, j)
Color_D = Color.FromArgb(255, Color_S.R, Color_S.G, Color_S.B)
map2.Setpixel(i, j, Color_D)

donc map1 = map2 normalement....et bien non : les coordonnées se trouvent decalées au fur et a mesure comme si cela ecrivait en diagonale....une idee ?

Merci.


Commentaire de ShadowTzu le 03/01/2008 13:16:36

je vais regarder ça, je crois que ça arrive que sur les images aillant une hauteur differente de la largeur.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Couleur SetPixel différente de couleure GetPixel sous Windows 2000 [ par cushy007 ] Couleur SetPixel différente de couleure GetPixel sous Windows 2000 [ par cushy007 ] Salut, J'ai un probl&#232;me sous Windows 2000 avec les couleurs des API SetPixel et GetPixel. La couleur que me renvoie GetPixel est diff&#233;rente GetPixel et SetPixel [ par MoiDebutantVB ] Je me rapelle avoir vu une source .Net qui utilisait GetPixel et Set Pixel ainsi qu'une Api et une autre méthode pour remplacer une couleur d'une bitm SetPixel place mal le pixel [ par baouc ] Bonjour à tous,voilà, je développe une appli sous vba depuis excel.Mon problème se situe au niveau d'une Userform (équivalent de la form), sur laquell reduire backdrop d'un mschart URGENT [ par monsieurlemouche ] bonjour,je cherche à donner des infos statistiques dans un flexgrid sous forme de courbe de gauss. Ne connaissant pas grand chose en programmation vb, Modif de la taille d'une Bitmap apres sa definition [ par doxt ] Peut ton redifinir la taille d'une bitmap apres sa definition Public Class Tutu    Private BM as New bitmap (10,10)    sub new        BM.height = Format8bppIndexed [ par loozer130467 ] bonjour,Une charmante personne pourait-elle m expliquer comment changer les pixelformat d un bmp ,svp ?sa fait maintenant 3 jour que je suis coincer s setpixel [ par jak12345 ] comment utiliser la methode setpixel? Sauvegarder un objet graphics... [ par MoiDebutantVB ] Bonjour !Comment faire pour charger un objet graphics dans un objet bitmap, pour ensuite sauvegader le bitmap ??? Merci Beaucoup en tout cas,CFP. image en degrade de gris [ par jak12345 ] Bonjour,Je veux declarer une image en degradé de gris puis affecter une teinte de gris à chacun de ses pixel. Mon code actuel est :         Dim Bitmap


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,905 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales