substraer color

(1/3) > >>

FJDA:
estoy intentado substraer el color de una imagen.

El objetivo es superponer un objeto PictureBox y hacer transparentar una parte de color verde de modo que se puedan ver objetos que hay debajo del PictureBox.

He intentado esto, pero lo único que consigo es un agujero en el formulario, ya que al transparentar el color verde de la imagen que está en el picture, también transparenta el formulario y se ve el escritorio, o cualquier cosa que haya debajo del formulario de la aplicación.


Código
Imports System
Imports System.Runtime.InteropServices
Imports System.Security
Imports System.Drawing.Imaging
 
Public Class Form1
   <DllImport("User32.dll", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function SetLayeredWindowAttributes(ByVal HWND As IntPtr, ByVal crKey As Integer, ByVal bAlpha As Byte, ByVal dwFlags As Integer) As Integer
   End Function
   <DllImport("User32.dll", EntryPoint:="GetWindowLongA", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function GetWindowLong(ByVal HWND As IntPtr, ByVal nIndex As Integer) As Integer
   End Function
   <DllImport("User32.dll", EntryPoint:="SetWindowLongA", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function SetWindowLong(ByVal HWND As IntPtr, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
   End Function
 
   Const GWL_EXSTYLE = (-20)
   Const WS_EX_LAYERED = &H80000
   Const GreenColor = &HFF00
 
   Private Function SubstractColor(ByVal HWND As IntPtr, Color As Integer) As Integer
 
       SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
       SetLayeredWindowAttributes(HWND, Color, 0, &H1)
       Return Nothing
   End Function
 
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       SubstractColor(Me.Handle, GreenColor)
   End Sub
End Class

Mi Net no tiene la System.Windows.Media que creo serviría para esto.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.color.subtract?view=netframework-4.8

Tampoco me funciona lo de backcolor = color. transparent, ni aún colocando imágenes con transparencia. Recuerdo que el objetivo es recortar o substraer una parte del PictureBox en la sección marcada por un determinado color.

Parece complicado

Serapis:
Qé tal si cambias tu código:
Citar

Private Function SubstractColor(ByVal HWND As IntPtr, Color As Integer) As Integer
 
        SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
        SetLayeredWindowAttributes(HWND, Color, 0, &H1)
        Return Nothing
    End Function

...por algo como lo siguiente:
Código
Private sub SubstractColor(ByVal HWND As IntPtr, Color As Integer, optional byval GradoTr as byte=128)
   SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
   SetLayeredWindowAttributes(HWND, Color, GradoTr , &H1)
End Function

Esto es, le estás diciendo que el nivel de transparencia sea total (valor 0), de momento prueba a invocarlo a mitad de transparencia entre el contenido y lo que haya debajo, es decir cada uno pone el 50% de la fuerza de su color. Puedes variar el valor entre 0 (transparente) y 255 (opaco).

p.d.: Prueba con valores de flags, 2 y 3 (no solo 1), de la api SetLayeredWindowAttributes, pués afectan a como se aplica a la imagen origen y la imagen subyacente...

FJDA:
Cita de: NEBIRE en 22 Abril 2019, 00:10 am

Qé tal si cambias tu código:
...por algo como lo siguiente:
Código
Private sub SubstractColor(ByVal HWND As IntPtr, Color As Integer, optional byval GradoTr as byte=128)
   SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
   SetLayeredWindowAttributes(HWND, Color, GradoTr , &H1)
End Function

Esto es, le estás diciendo que el nivel de transparencia sea total (valor 0), de momento prueba a invocarlo a mitad de transparencia entre el contenido y lo que haya debajo, es decir cada uno pone el 50% de la fuerza de su color. Puedes variar el valor entre 0 (transparente) y 255 (opaco).



Se agradece la respuesta pero esto que propones es incorrecto en todo caso.

Te lo explico
Citar

   <DllImport("User32.dll", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
    Private Shared Function SetLayeredWindowAttributes(ByVal HWND As IntPtr, ByVal crKey As Integer, ByVal bAlpha As Byte, ByVal dwFlags As Integer) As Integer
    End Function



El último valor que he marcado en rojo (dwFlags) de la función  SetLayeredWindowAttributes, puede tener dos valores según el objetivo a aplicar. Que serían

Código
 
Const LWA_COLORKEY As Long = &H1
Const LWA_ALPHA As Long = &H2
 

Si uso &H1  el valor de bAlpha para la función sólo significa una asignación de color para sustraer

Si aplico &H2  es decir LWA_COLORKEY, entonces  bAlpha representaría un valor de nivel de transparencia que afectaría a TODO el formulario y no solo al color.

Código
 
   Private Sub SubstractColor(ByVal HWND As IntPtr, Optional ByVal GradoTr As Byte = 128)
       SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
       SetLayeredWindowAttributes(HWND, IntPtr.Zero, GradoTr, LWA_ALPHA)
   End Sub
 



El código quedaría de la siguiente manera:
Código
Imports System
Imports System.Runtime.InteropServices
Imports System.Security
Imports System.Drawing.Imaging
 
Public Class Form1
   <DllImport("User32.dll", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function SetLayeredWindowAttributes(ByVal HWND As IntPtr, ByVal crKey As Integer, ByVal bAlpha As Byte, ByVal dwFlags As Integer) As Integer
   End Function
   <DllImport("User32.dll", EntryPoint:="GetWindowLongA", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function GetWindowLong(ByVal HWND As IntPtr, ByVal nIndex As Integer) As Integer
   End Function
   <DllImport("User32.dll", EntryPoint:="SetWindowLongA", CharSet:=CharSet.Unicode), SuppressUnmanagedCodeSecurityAttribute>
   Private Shared Function SetWindowLong(ByVal HWND As IntPtr, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
   End Function
 
   Const GWL_EXSTYLE = (-20)
   Const WS_EX_LAYERED = &H80000
   Const GreenColor = &HFF00
   Const LWA_COLORKEY As Long = &H1
   Const LWA_ALPHA As Long = &H2
 
   Private Sub SubstractColor(ByVal HWND As IntPtr, Optional ByVal GradoTr As Byte = 128)
       SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
       SetLayeredWindowAttributes(HWND, IntPtr.Zero, GradoTr, LWA_ALPHA)
   End Sub
   'Private Function SubstractColor(ByVal HWND As IntPtr, Color As Integer) As Integer
   '    SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
   '    SetLayeredWindowAttributes(HWND, Color, 0, LWA_COLORKEY)
   '    Return Nothing
   'End Function
 
   Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
       SubstractColor(CType(Me.Handle, IntPtr), 210)
   End Sub
End Class
 


Pero esto aplica el nivel de transparencia a todo el formulario. Por desgracia no se puede limitar  a un determinado color.



y si hago lo siguiente hace las dos cosas, sustrae el color asignado al 100% dejándolo todo transparente, excepto el resto del formulario que queda semi-transparente

Código
Private Sub SubstractColor(ByVal HWND As IntPtr, Optional ByVal GradoTr As Byte = 128)
       SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
       SetLayeredWindowAttributes(HWND, GreenColor, GradoTr, LWA_ALPHA + LWA_COLORKEY)
   End Sub
 


mejor:
Código
   Private Sub SubstractColor(ByVal HWND As IntPtr, ByVal Color As Integer, Optional ByVal GradoTr As Byte = 128)
       SetWindowLong(HWND, GWL_EXSTYLE, GetWindowLong(HWND, GWL_EXSTYLE) Or WS_EX_LAYERED)
       SetLayeredWindowAttributes(HWND, Color, GradoTr, LWA_ALPHA + LWA_COLORKEY)
   End Sub
 


Encontré una persona que quiso hacer lo mismo aquí
http://forums.codeguru.com/showthread.php?477962-Tranparent-color

no se puede hacer, al menos de una forma sencilla, tengo alguna idea pero va para rato. Sería creando un objeto COM o una nueva ventana incrustada en la aplicación mediante código.

Serapis:
Cita de: FJDA en 22 Abril 2019, 00:42 am

Se agradece la respuesta pero esto que propones es incorrecto en todo caso.

Te lo explico...



Ante tu queja, te vuelvo a leer... y sí, leo tu no quieres que la transparencia se aplique sobre el escritorio. Me dejé llevar por las API que estás usando y que en general se utilizan para generar ventanas con forma irregular y transparencias en bordes, etc...

Hay varias formas de proceder, según lo que precises...
Por ejemplo puedes tener un objeto que admita gráficos (para el ejemplo un picturebox con una imagen precargada en su 'backgroundimage', si lo prefieres puede no tenerla y entonces lo que se verá será su BackColor), y puedes dibujar una imagen procedente de (por ejemplo) otro picturebox, aplicando transparencia a un color...

Aquí un código de ejemplo (y debajo algunas notas):
Código
Private Sub BtnTransparentar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnTransparentar.Click
   Dim Iat As New System.Drawing.Imaging.ImageAttributes
   Dim dstRect As Rectangle = PictureBox1.DisplayRectangle
   Dim d2rect As Rectangle
   Dim g As System.Drawing.Graphics = PictureBox1.CreateGraphics
 
   Iat.SetColorKey(Color.Fuchsia, Color.Fuchsia) ' un 1 unico color, puede definirse un rango...
 
   ' Nota como solo se transaprentará lo que se pegue de color rosa chicle, no lo que en destino ya hubiere de dicho color.
   d2rect.Size = New Size(dstRect.Width \ 8, dstRect.Height \ 8)
   d2rect.Location = New Point(60, dstRect.Height \ 6)
   g.FillEllipse(Brushes.Fuchsia, d2rect)
 
   g.DrawImage(PictureBox2.Image, dstRect, 0, 0, PictureBox2.Width, PictureBox2.Height, GraphicsUnit.Pixel, Iat)
End Sub
 

La imagen 1 muestra ambos picturebox, en realidad el 2º está oculto en tiempo de ejcución, da igual si no existe y lo tomas desde recursos, o lo cargas directamente desde fichero, yo he ido a los simple para el ejemplo, por lo mismo ambas imágenes son casi del mismo tamaño (creo), hay varias sobrecargas para elegir el método que mejor se ajuste a tus necesidades, nota sin embargo que la sobrecarga que eleijas debe tener el parámetro "imageattributes", para aplicar como color transparente (colorKey), el color o el rango entre colores deseados.
También para el ejemplo, la imagen de origen es bmp, así para el color rosa chicle existe la seguridad que es ese, si se comprime la imagen a jpg, habrá múltiples colores muy similares...


La segunda imagen,  es como aparece al iniciar la ventana... nota que el tamaño de la ventana ahora está reducida, en la imagen anterior tenía el único propósito de mostrar el picturebox2.


La tercera imagen contiene ya aplicado pegar la imagen y aplicada la transparencia...
Nota que antes de pegar la imagen dibujamos una elipse del mismo color que el transparente (sobre una zona que luego queda transparente), para dejar claro que el color transparente se aplica solo sobre la imagen de origen.


Nota que el destino, puede ser igualmente cualquier otro objeto que admita control gráfico, el form, un panel, etc... y nota que siempre se mantiene el orden gráfico, es decir esto al ser un método, se pegará sienpre en la capa del fondo, es decir en el hDC del control, luego si hay un contenedor que tiene por ejemplo un botón encima, no afecta a su hDc, ese botón está por encima en la capa gráfica que el hDC del contenedor... por eso este método, no soluciona todos los casos, solo cuando es dentro del mismo objeto con gráficos al mismo nivel gráfico.

Pueden hacerse diferentes cosas, pero según de que se trate debe tomarse una orientación distinta, en general deberá usarse máscaras y utilizar operaciones de blitting usando las operaciones de rasterización adecuadas.

FJDA:
NEBIRE muchas gracias antes de nada.

Pero eso no es lo que intentaba. El objetivo es recortar, eliminar una porción de un control Picturebox dejándolo transparente de tal modo que se puedan ver otros controles que hubieran debajo del Picturebox,  SetLayeredWindowAttributes solo funciona con ventanas no funciona por ejemplo usando Picturebox1.Handle. DrawImage solo afecta a imágenes aplicadas al Picturebox pero no al objeto en cuestión.  

No existe en NET ningún método para hacer eso que yo sepa, la única manera es recurrir a APIs de Windows. Conozco una forma de recortar partes de un control pero si quiero darle una forma concreta es complicado, de ahí que partiera usando un color. Quizás con éste método pudiera eliminar solo los píxeles que contengan un determinado color.

Otra forma sería  creando un objeto COM y a esperar que SetLayeredWindowAttributes  solo afecte a este y no al formulario que lo contiene. También se me ocurre crear un formulario mediante código e incrustarlo en el formulario principal. A ver si esto funciona. Creo que otra forma sería usar GDI32 pero no se nada de eso parece complicado.



ya he probado la primera opción se podría decir que hace lo que quiero pero tiene una extraño comportamiento, además una vez elimino la zona verde se vuelve el picture se vuelve a dibujar, tiene autoredraw. También realiza el proceso muy lentamente ya que va eliminando pixel por pixel. Igualmente lo posteo por si alguien tiene curiosidad o lo puede arreglar.

Código
Imports System
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Drawing.Color
Public Class Form1
   <DllImport("gdi32")> _
   Private Shared Function CreateRectRgn(ByVal X1 As Integer, ByVal Y1 As Integer, ByVal X2 As Integer, ByVal Y2 As Integer) As Integer
   End Function
   <DllImport("gdi32.dll", CharSet:=CharSet.Auto)> _
   Private Shared Function CreateEllipticRgn(ByVal X1 As Integer, _
                   ByVal Y1 As Integer, ByVal X2 As Integer, ByVal Y2 As Integer) As Integer
   End Function
 
   <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
   Private Shared Function SetWindowRgn(ByVal hwnd As IntPtr, ByVal hRgn As Integer, ByVal bRedraw As Boolean) As Integer
   End Function
 
   <DllImport("user32.dll", Entrypoint:="SendMessageA", CharSet:=CharSet.Auto)>
   Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As StringBuilder) As IntPtr
   End Function
 
   <DllImport("user32.dll", CharSet:=CharSet.Auto)>
   Private Shared Function ReleaseCapture() As Integer
   End Function
 
   <DllImport("gdi32.dll")>
   Private Shared Function CreatePolygonRgn(ByVal lppt As Point(), ByVal cPoints As Integer, ByVal fnPolyFillMode As Integer) As IntPtr
   End Function
 
 
   Const WM_NCLBUTTONDOWN = &HA1
   Const HTCAPTION = 2
   Public Const ALTERNATE = 1
 
 
   Public Structure POINTAPI
       Dim x As Integer
       Dim y As Integer
   End Structure
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
 
 
 
   End Sub
 
   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
 
       '//Obtiene la localización X Y de los píxeles de color Verde RGB(0, 255, 0)
       Dim b As Bitmap = New Bitmap(PictureBox1.Image)
       Dim xPosPixel As Integer = Nothing
       Dim yPosPixel As Integer = Nothing
 
       Dim gp As New Bitmap(b.Width, b.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)
       For Y As Integer = 0 To gp.Height - 1
           For X = 0 To gp.Width - 1
               Dim cw As New Color
               cw = Color.Lime 'Verde RGB(0, 255, 0)
               Dim curPixColor As Color = b.GetPixel(X, Y)
               If curPixColor.ToArgb() = cw.ToArgb() Then
                   'Elimina el píxel
                   ClipPixel(X, Y)
               End If
           Next
       Next
 
   End Sub
 
   Public Sub ClipPixel(ByVal X As Integer, ByVal Y As Integer)
       Dim lpPts(12) As Point
 
       Dim hRustedRgn As Long  ' Rusted region
       Dim WPicture As Integer
       Dim HPicture As Integer
       Dim X1, X2, Y1, Y2 As Integer
      WPicture = PictureBox1.Width
       HPicture = PictureBox1.Height
       X1 = X : X2 = Y : Y1 = Y : Y2 = Y + 1
 
       ' Fill out the Rusted region points
       ' The starting point
       lpPts(0).X = 0 : lpPts(0).Y = 0
       ' The width from the starting point
       lpPts(1).X = WPicture : lpPts(1).Y = 0
       ' The height from the Width
       lpPts(2).X = WPicture : lpPts(2).Y = HPicture
       ' The Height from the starting point
       lpPts(3).X = 0 : lpPts(3).Y = HPicture
       ' Create half of the square as a Triangle
       lpPts(4).X = 0 : lpPts(4).Y = X1
       lpPts(5).X = X1 : lpPts(5).Y = X1
       lpPts(6).X = X1 : lpPts(6).Y = Y1
       lpPts(7).X = X2 : lpPts(7).Y = Y1
       lpPts(8).X = X2 : lpPts(8).Y = Y2
       lpPts(9).X = X1 : lpPts(9).Y = Y2
       lpPts(10).X = X1 : lpPts(10).Y = X1
       lpPts(11).X = 0 : lpPts(11).Y = X1
 
       hRustedRgn = CreatePolygonRgn(lpPts, lpPts.Length, ALTERNATE)
       Call SetWindowRgn(PictureBox1.Handle, hRustedRgn, True)
   End Sub
End Class
 

Curiosamente este código en VB6 funciona mejor. En VB6 los objetos que hay debajo del Picture, como un botón se ven correctamente cuando eliminas la zona de color verde, además una vez eliminado el efecto se mantiene, pero en VB.NET justamente los objetos se vuelven de color verde y el picture se vuelve a redibujar. No funciona  :-\





Navegación

[0] Índice de Mensajes

[#] Página Siguiente