Subscribe to Random Programs I've created/altered.        RSS Feed
-----

Image Opacity Alteration

Icon Leave Comment
I have searched all over the internet for something explaining how to alter an images opacity, since the "Image" object doesn't have an Opacity property. I've finally found a piece of code written in C# located here Change Opacity of Image, that I've transformed into VB.Net, to use in one of my applications.

Imports System.Drawing.Imaging

Public Class Form1
  ''' <summary>  
  ''' method for changing the opacity of an image  
  ''' </summary>  
  ''' <param name="image">image to set opacity on</param>  
  ''' <param name="opacity">percentage of opacity</param>  
  ''' <returns></returns>
  Private Function SetImageOpacity(ByVal image As Image, ByVal opacity As Double) As Image
    Try
      Dim bmp As Bitmap = New Bitmap(image.Width, image.Height)
      Using gfx As Graphics = Graphics.FromImage(bmp)

        Dim matrix As New ColorMatrix()
        matrix.Matrix33 = Convert.ToSingle(opacity)
        Dim attributes As New ImageAttributes()
        attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap)
        gfx.DrawImage(image, New Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes)
      End Using
      Return bmp
    Catch ex As Exception
      MessageBox.Show(ex.Message)
      Return Nothing
    End Try
  End Function

  Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
    Dim origImage As Image = PictureBox1.Image
    ' use this if you want to fade in a different image than the original.
    'Dim newImage As Image
    'newImage = Image.FromFile("picture path")
    For d As Double = 1 To 0 Step -0.05
      PictureBox1.Image = SetImageOpacity(PictureBox1.Image, d)
      PictureBox1.Refresh()
      System.Threading.Thread.Sleep(50)
    Next
    For d As Double = 0 To 1 Step 0.05
      PictureBox1.Image = SetImageOpacity(origImage, d)
      PictureBox1.Refresh()
      System.Threading.Thread.Sleep(50)
    Next
  End Sub
End Class



Below is the attached project with source code. It's not a pretty layout, because this was just a test. You will also need to change the directory for where the pictures are located on your machine that you wan to loop through.

Attached File(s)

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

August 2014

S M T W T F S
     12
3456789
10111213141516
17181920 21 2223
24252627282930
31      

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)