ASP.NET Image Manipulation Examples: Adding, Zooming, Enlarging

來源:互聯網
上載者:User
文章目錄
  • Multiple zooms..
  • Change 1:

摘至: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 'enlarging images'.

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 our src="" attribute of the <img> tag.

&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 would 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 using the Drawing namespace and the GDI/ GDI+ libraries... you should 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 would create a separate file such as imager.aspx and put no controls or anything on it... but just code for the Page_Load event as below:

private void Page_Load(object sender, System.EventArgs e){Bitmap objImage = new Bitmap(strBasePath + file://images//fruity.jpg);objImage.Save(Response.OutputStream,ImageFormat.Jpeg);objImage.Dispose();}

The above code loads an image from the images directory of the web project and pushes it to the OutputStream which 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 = <span class="cs-keyword">new</span> Bitmap(<span class="cs-literal">23</span>,<span class="cs-literal">15</span>);oGraphics = Graphics.FromImage(oCounter);Bitmap objImage = <span class="cs-keyword">new</span> Bitmap(strBasePath + <a href="file://images//1.gif">file:<span class="cs-comment">//images//1.gif</span></a>);oGraphics.DrawImage(objImage,<span class="cs-literal">0</span>,<span class="cs-literal">0</span>);objImage = <span class="cs-keyword">new</span> Bitmap(strBasePath + <a href="file://images//2.gif">file:<span class="cs-comment">//images//2.gif</span></a>);oGraphics.DrawImage(objImage,<span class="cs-literal">11</span>,<span class="cs-literal">0</span>);
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 of the drawimage() method, attributes... int X, and int Y.

If you are wondering why I named the final image object oCounter: typical application of adding two images would 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 using an ImageButton aspx 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 source Rectangle (defining which portion is to be drawn),
  • a destination Rectangle (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, oItemp contains the image... the rest is clear I suppose.

Zoom - effect Logic

I think I should 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 should 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 at 322,123, then in the second postback of the form, I scale the image twice using a for loop every time at the respective points.

Hope that sounds clear. Anyways, the code is also well-documented.. 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 with the DrawImage() method, it also can happen when you load the image.

Steps:
  1. load an image to actual size
  2. create an Image object 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 class Bitmap.

But when I tried the zoom-effect Ex:2, the Bitmap object won't scale to a new size whatever I do, .. but good fortunes, auto-scaling happened with the Image object.

The problem was with the DrawImage() method which would 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 would 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:

<span class="cs-comment">//in index.aspx.cs page</span><span class="cs-keyword">private</span> <span class="cs-keyword">void</span> Button1_Click(<span class="cs-keyword">object</span> sender, System.EventArgs e){ImageButton1.ImageUrl=<span class="cpp-string">"imager.aspx"</span>;txtPosX.Value=<span class="cpp-string">""</span>;txtPosY.Value=<span class="cpp-string">""</span>;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.