ASP. NET image manipulation examples: adding, zooming, enlarging

Source: Internet
Author: User
ArticleDirectory
    • Multiple zooms ..
    • Change 1:

Abstract: http://www.codeproject.com/aspnet/ASPImaging1.asp
Download source files-32.3 KB

Introduction

This is a sample project to do image manipulation in ASP. NET projects, using. Net's GDI library, and related classes.

The project demonstrates dynamically'Adding two images','Creating zoom effects', And'Enabledimages'.

Some Notes on displaying dynamically generated images

If we have to generate an image dynamically and show it on a webpage, we have to do the image generation coding on a separate page and call it in ourSrc = ""Attribute ofTag.

& Lt; IMG src = "imager. aspx"/& gt;

This is the common and as-far-as I know, the only way to display dynamic images on a webpage, and not specific to the ASP. net Framework alone. it applies to whatever language and Webserver you might use. and fortunately, this method is compliant with any client browser, since the process happens server-side.

Generating Images

You wowould typically use all (or some) of the below. Net namespaces to generate/load preexisting images.

<SPAN class = "CS-keyword"> using </span> system. drawing; <SPAN class = "CS-keyword"> using </span> system. drawing. imaging; <SPAN class = "CS-keyword"> using </span> system. drawing. drawing2d;

You can draw lines, arcs and do a lot of things usingDrawingNamespace and the GDI/GDI + libraries... You shoshould see articles on the same for doing that. In this article, we will only try manipulating pre-existing images.

The rest of this article will use classes and methods in the above mentioned namespaces.

Loading and displaying an image

To load and display an image, you wocould create a separate file suchImager. aspxAnd put no controls or anything on it... but just code forPage_loadEvent as below:

Private VoidPage_load (Object sender, system. eventargs e) {bitmap objimage =NewBitmap (strbasepath + file:// Images // fruity.jpg); Objimage. Save (response. outputstream, imageformat. JPEG); objimage. Dispose ();}

The above code loads an image fromImagesDirectory of the web project and pushes it toOutputstreamWhich is the response header that will be sent to the client.

Done that, we can put a call to the image as mentioned before:

& Lt; IMG src = "imager. aspx"/& gt;
Ex1: adding two images

Having discussed displaying a single image .. it's very obvious now as to how to add two images and send to the client.

The simplest way being to push two images to the response stream. Or you can add the two images to a new image and push this image to the response stream as below:

Bitmap ocounter; graphics ographics;
 ocounter =  New  Bitmap ( 23 ,  15 ); ographics = graphics. fromimage (ocounter); bitmap objimage =  New  Bitmap (strbasepath +  file:  // images // 1.gif ); ographics. drawimage (objimage,  0 ,  0  ); objimage =  New  Bitmap (strbasepath +  file:  // images // 2.gif ); ographics. drawimage (objimage,  11 ,  0  ); 
Ocounter. Save (response. outputstream, imageformat. JPEG); objimage. Dispose (); ocounter. Dispose ();

Note: When drawing the second image, it's important to paste it at the proper position .. or else it overwrites or draws itself over the old image... this we do by manipulating the top left position ofDrawimage ()Method, attributes...IntX, AndIntY.

If you are wondering why I named the final image objectOcounter: Typical application of adding two images wocould be generating 'Hit counter 'images for your clients.

Ex2: zooming Images

There are two ways of zooming an image... or rather bringing out a zoom-effect on images.

    1. Enlarge the image to a larger size (this is discussed in the EX3 ).
    2. Copy a portion of the image and enlarge it to the size of the original image.

We discuss method (2) here.

In the sample project, I create the image usingImagebuttonAspx control. This is to allow users to click on the image and pass x, y Params to the server so that the clicked area of the image is zoomed (or technically enlarged ).

The only function to learn to do this is:

Graphics. drawimage ()

Drawimage ()Accepts:

    • A sourceRectangle(Defining which portion is to be drawn ),
    • A destinationRectangle(Defining the target size and position of the image ).

And if the destination rectangle is larger than the source rectangle,. Net automatically scales the image thereby getting our zooming effect.

Yes! This is important :"Drawimage ()Scales the image automatically if needed ".

<SPAN class = "CS-comment"> // get the portion of image (defined by sourcerect) </span> <SPAN class = "CS-comment"> // and enlarge it to desrect size... gives a zoom effect. </span> <SPAN class = "CS-comment"> /// if image has high resolution .. effect will be good. </span> ographics. drawimage (oitemp, desrect, sourcerect, graphicsunit. pixel );

In the above code block,OitempContains the image... the rest is clear I suppose.

Zoom-effect logic

I think I shocould explain the logic I have used in my code (downloadable with this article-see top of article for download link ).

What I do is I handle the image button click event, and get the X, Y position where the user clicked on the image. I then do some basic calculation and mark my source rectangle around this click point... my source rectangle is 60% the size of the actual image itself. since we discussed that source rectangle shocould be somewhere smaller than the destination rectangle for the scaling to happen. may be you can have a 50% size also, in which case the image gets zoomed more...

<SPAN class = "CS-keyword"> float </span> iportionwidth = (<SPAN class = "CS-literal"> 0 </span>. 60f * Oi. width); <SPAN class = "CS-keyword"> float </span> iportionheight = (<SPAN class = "CS-literal"> 0 </span>. 60f * Oi. height); <SPAN class = "CS-comment"> // oi is the image. </span>
Multiple zooms ..

I allow the user to click on the enlarged image also .. That means zoom it further and further. I achieved this with the below logic:

I have two hidden fields on the form .. where I store the user clicked positions like:

Xpos = 100 ypos = 200

On the second click, the hidden fields take the values:

Xpos = 100,322 ypos = 200,123

And so on .. so I have a track of all the clicks the user made. I then split this string of values and perform the zoom operation on the original image multiple times.

That means, if user clicked at 100,200 first time and on the zoomed image he clicked ed at 322,123, then in the second PostBack of the form, I scale the image twice usingForLoop every time at the respective points.

Hope that sounds clear. Anyways, the Code is also well-formed ented... and you will see it work as you break-into the code.

EX3: enlarging the image (zoom-effect 2)

Auto-scaling doesn' t alone happen withDrawimage ()Method, it also can happen when you load the image.

Steps:
    1. Load an image to actual size
    2. CreateImageObject and load the object (from Prev step), with a width and height
Bitmap oimg, oimgtemp; oimgtemp = <SPAN class = "CS-keyword"> New </span> Bitmap (strbasepath + <a href = "file: // images // fruity.jpg "> file: <SPAN class =" CS-comment "> // images // fruity.jpg </span> </a> ); oimg = <SPAN class = "CS-keyword"> New </span> Bitmap (oimgtemp, <SPAN class = "CS-literal"> 600 </span>, <SPAN class = "CS-literal"> 400 </span> );

That's it .. the result is an enlarged image.

Observation:

I worked through this example creating all bitmap objects from the classBitmap.

But when I tried the zoom-Effect Ex: 2,BitmapObject won't scale to a new size whatever I do,... but good fortunes, auto-scaling happened withImageObject.

The problem was withDrawimage ()Method which wocould not do auto-scaling for bitmap image objects (supplied as the first argument )..

Hence, the below wont work.

<SPAN class = "CS-comment"> // obitmap is an instance of class 'bitmap' </span> ographics. drawimage (obitmap, desrect, sourcerect, graphicsunit. pixel );

While, this will...

<SPAN class = "CS-comment"> // oitemp is an instance of class 'image' </span> ographics. drawimage (oitemp, desrect, sourcerect, graphicsunit. pixel );
Change History: Change 1:

Suppose you zoom the image (in ex2) once or twice, and then click button 'original' and then again zoom once .. you will see the wrong result. it wowould have zoomed once + NO. of times zoomed earlier before pressing 'original '. the problem is I am not clearing the hidden fields when 'original' button is pressed.

I forgot this... really.: O)

I have now updated the download on this page (as on 8/APR/04) .. if u don't have the new download... the only correction is:

  // in index. aspx. CS page   private   void  button#click ( Object  sender, system. eventargs e) {imagebutton1.imageurl =  "imager. aspx "; txtposx. value =  "" ; txtposy. value =  "" ;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.