imageflip.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Image" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Create a bitmap object and load the background image from a file
Dim myBitmap As Bitmap
myBitmap = New Bitmap(System.Drawing.Image.FromFile(Server.MapPath("images/imageflip.jpg")))
' The original image is loacted here for comparison:
' http://www.asp101.com/samples/images/imageflip.jpg
' I'm now going to flip the picture from left to right. You'd normally
' just use the built-in RotateFlip method to do this, but I want to
' illustrate looping over the picture pixel by pixel for those of you
' who may need to apply more advanced tranformations.
' FYI: the simple version looks like this:
'myBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX)
' Now on to the more complex home-grown version:
Dim X, Y As Integer
Dim colorTempSwap As Color
Dim myPixelColor As Color
' Loop over rows
For Y = 0 To myBitmap.Height - 1
' Loop over columns
For X = 0 To myBitmap.Width - 1
' Since I'm swapping each pixel with the pixel on opposite side
' of the image as I go, I only want to perform the swap up until
' I get half way across or else I'd end up swapping them back
' to where they started.
If X < Int((myBitmap.Width - 1) / 2) Then
' If the swap was the only operation you were doing on the
' image you could consolidate the For and If statements above
' into one line and only loop halfway across each row:
' For X = 0 To Int((myBitmap.Width - 1) / 2)
' Pixel swapping code:
' Retrieve and temporarily store the current pixel's color.
colorTempSwap = myBitmap.GetPixel(X, Y)
' Set the current pixel's color to the color of the
' pixel's "mirror" on the other side of the image.
myBitmap.SetPixel(X, Y, myBitmap.GetPixel((myBitmap.Width - 1) - X, Y))
' Set the "mirror" pixel's color to the original color
' of the current pixel which we saved above.
myBitmap.SetPixel(myBitmap.Width - 1 - X, Y, colorTempSwap)
End If
' If you need to, it's easy to do operations to modify things.
' Some examples:
' Replace "White" pixels with "Red" pixels. You won't get
' many/any exact matches like this in most images. This
' type of thing is really only useful if you create the
' image from scratch.
If myBitmap.GetPixel(X, Y).ToArgb = Color.White.ToArgb Then
myBitmap.SetPixel(X, Y, Color.Red)
End If
' Cut down the red component of the picture some.
' Gives it a nice blue-green tint:
myPixelColor = myBitmap.GetPixel(X, Y)
myBitmap.SetPixel(X, Y, Color.FromArgb(myPixelColor.R / 1.2, myPixelColor.G, myPixelColor.B))
Next
Next
' Set response header to correct file type
' Save the file to output stream to be displayed in browser
Response.ContentType = "image/jpeg"
myBitmap.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
' Flush the Response
Response.Flush()
End Sub
</script>