简体   繁体   中英

Convert Picturebox Image to Transparent VB.Net

I'm having a problem when it comes to images with white background. How can I remove the white background or make the image transparent?

For now I'm using this code

Dim _ms3 As New System.IO.MemoryStream()
pbSignCapture.Image.Save(_ms3, System.Drawing.Imaging.ImageFormat.Png)
Dim _arrImage3() As Byte = _ms3.GetBuffer()
_ms3.Close()

Also saving the image using the _arrImage3 .

I want to convert the image in the PictureBox to turn the White Background into transparent.

Consider using the Bitmap class to open your image files.

Dim myImage as new Bitmap("C:\Image file.bmp")

And then you can use the MakeTransparent() or MakeTransparent(Color) methods:

Get the color of a background pixel.

Dim backColor As Color = myImage.GetPixel(1, 1)

Make backColor transparent for myBitmap.

myImage.MakeTransparent(backColor)

EDIT:

As I understand from the new details you want to have a PictureBox to be transparent where the source image is transparent. Unfortunately this is not possible using WinForms because the transparency system is not cascading. You can set the BackgroundColor property of pictureBox to transparent, but this is going to act differently from what you may think. The free pixels of the PictureBox control will show the content of the parent control .

It means that if you have, for example, a label below your picurebox and set transparent background to the image; the label won't be shown because it is not theparent control of the picturebox.

A workaround is to manually draw the image in the paint event of the destination control.

Let's assume that you have a form with many controls and you want to draw ad image over a button (named btn). You'll have to override the form's paint event this way:

Private Sub form_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles form.Paint
    Dim g As Graphics = e.Graphics    
    g.DrawImage(Image.FromFile("C:/yourimage.png", btn.Location.X, btn.Location.Y)
End Sub 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM