Ahmad Masykur

Share your knowledge although one function!

About the author

Ahmad Masykur is a Software Architecture Engineer at PT. Freeport Indonesia Jakarta Indonesia.
In this blog, I share things of interest to me. Most topics are likely to be related to software development, but don't hold me to it.

Certificates



Awards


Powered by

Prayer Time

February 10, 2010
الفجر/Dawn 04:36:44
الشروق/Sunrise 05:56:43
الظهر/Noon 12:06:58
العصر/Afternoon 15:23:10
المغرب/Sunset 18:17:13
العشاء/Dusk 19:28:46
Jakarta  Indonesia
Prayer time widget created by
Ahmad Masykur

Page List

Validators


Ahmad Masykur

Membuat HttpHandler untuk Resize Image

Ketika membuat sebuah galeri foto, sering kali harus membuat beberapa versi ukuran foto. Foto-foto kecil ditampilkan secara berjajar. Ketika foto diklik, akan muncul foto dengan ukuran besar. Pada waktu slide-show, maka foto ukuran sedang yang ditampilkan. Untuk membuat foto dengan ukuran yang bermacam-macam dapat dilakukan dengan merubah ukuran secara run-time.

Berikut adalah class untuk melakukan resize ukuran image.

public class PhotoManager {
    public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) {
        using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) {
            Size newSize = CalculateDimensions(oldImage.Size, targetSize);
            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)) {
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

    private static Size CalculateDimensions(Size oldSize, int targetSize) {
        Size newSize = new Size();
        if (oldSize.Height > oldSize.Width) {
            newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
            newSize.Height = targetSize;
        } else {
            newSize.Width = targetSize;
            newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
        }
        return newSize;
    }
}

Dalam kode di atas, targetSize merupakan target panjang image yang akan diperoleh. Untuk mengirimkan gambar ke client, dibutuhkan sebuah handler.

Berikut adalah handler mengirimkan image ke client. Kode dibawah disimpan dalam file dengan extention .ashx yang akan dikerjakan oleh web server sebagai sebuah web handler.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.IO;
using System.Web;

public class Handler : IHttpHandler {

	public bool IsReusable {
		get {
			return true;
		}
	}
	
	public void ProcessRequest (HttpContext context) {
		// Set up the response settings
		context.Response.ContentType = "image/jpeg";
		context.Response.Cache.SetCacheability(HttpCacheability.Public);
		context.Response.BufferOutput = false;
		// Get photo from file system
        string filename = context.Request.QueryString("FileName");
        if (filename != null)
        {
            using (FileStream fileStream = new FileStream(context.Server.MapPath("images\\" + filename)))
            {
                using (BinaryReader reader = new BinaryReader(fileStream))
                {
                    byte[] imageFile = reader.ReadBytes(fileStream.Length);
                    byte[] stream;
                    stream = (context.Request.QueryString("Size") != null) ? PhotoManager.ResizeImageFile(imageFile, int.Parse(context.Request.QueryString("Size"))) : imageFile;
                    // Write image stream to the response stream
                    const int buffersize = 1024 * 16;
                    byte[] buffer = new byte[buffersize];
                    int count = stream.Read(buffer, 0, buffersize);
                    while (count > 0)
                    {
                        context.Response.OutputStream.Write(buffer, 0, count);
                        count = stream.Read(buffer, 0, buffersize);
                    }
                }
            }
        }
    }
}

Pada halaman web tinggal panggil handler yang telah dibuat dengan querystring nama file dan ukuran image.

<img src="Handler.ashx?FileName=myimage.jpg&Size=320"style="border:4px solid white" alt="My Image" />

Categories: ASP.NET
Permalink | Comments (13) | Post RSSRSS comment feed

Comments

Ali Faiq Indonesia | Reply

Tuesday, July 31, 2007 5:18 AM

Ali Faiq

Assalamu'alaikum

Script yang bagus pak, namun bisa gak di implemen ke web saya yang berbasis html (hosting di geocities). Trimakasih.

Wssalamu'alaikum

Ahmad Masykur Indonesia | Reply

Tuesday, July 31, 2007 7:33 AM

Ahmad Masykur

Wa'alaikum salam
Namanya saja dynamic web application ya harus ada mesin yang menjalankannya. Kode saya tersebut menggunakan C# di atas ASP.NET. Kalo mo ngecilin tampilan saja (bukan ukuran sebenarnya) bisa pake HTML dengan set width dan height di attribut <img.
Wassalam

hanafi Indonesia | Reply

Tuesday, July 31, 2007 5:59 PM

hanafi

ingin membuat situs yang bagus

iqranagera United States | Reply

Monday, April 07, 2008 10:17 AM

iqranagera

Saya sedang cari cara untuk mengubah ukuran gambar di client side. Website saya pake image resizer berbasis PHP. Otomatis akan memberatkan server. Bisa tidak proses resize itu dilakukan di komputer klien sebelum gambar diupload agar lebih ringan.

Ahmad Masykur Indonesia | Reply

Monday, April 07, 2008 10:28 AM

Ahmad Masykur

Jawabannya tidak bisa. Karena di client hanya bisa jalankan JavaScript (kecuali client mengijinkan untuk jalankan ActiveX object [IE only]) dan JavaScript hanya mengenal string, numeric, boolean, array dan object. Anda bisa memaksa client untuk tidak mengupload file dengan ukuran besar dengan membatasi request size.
Sebenarnya server tidak terlalu terbebani jika hanya untuk meresize image, beban lebih besar di trafik jaringan jika ukuran file sangat besar.

Dewa United States | Reply

Monday, May 05, 2008 11:05 AM

Dewa

maaf, ikutan nimbrung.
bisa kok resize image pake javascript.
lebih tepatnya nge-stretch image ke ukuran yang kita inginkan.
baca-baca aja di http://www.w3schools.com bagian HTMLDOM

tapi yang saya bingung, kenapa scriptnya ga jalan di IE7.
padahal saya coba di mozilla firefox bisa.
ada yang bisa bantu saya mencari jawabannya ?

Ahmad Masykur Indonesia | Reply

Monday, May 05, 2008 11:18 AM

Ahmad Masykur

Resize pake javascript hanya merubah tampilan saja. Ukuran file tidak berubah. Tanpa javascript, dengan mengeset width dan height pada tag <img> sudah bisa merubah tampilan gambar. Contoh handler yang saya gunakan ditujukan untuk merubah ukuran gambar dan file sehingga saat didownload, ukuran file tidak terlalu besar.
Script yang anda gunakan tidak jalan di IE7, bisa post contoh script Anda supaya bisa dibantu mencarikan pemecahannya.

Aryanto Indonesia | Reply

Sunday, June 22, 2008 10:32 AM

Aryanto

Pak, gimana kalo image resize pakai image magick with ASP. coz bingung nyari panduannya. Thanx!

Busby SEO Test United States | Reply

Saturday, December 06, 2008 10:30 PM

Busby SEO Test

thanks for this code. love it

seo test! United States | Reply

Sunday, January 25, 2009 2:04 AM

seo test!

nambah satu ilmu lagi neh... makasih om Laughing

Rockaway, NJ Mercedes Benz Repairs United Kingdom | Reply

Thursday, February 05, 2009 9:05 PM

Rockaway, NJ Mercedes Benz Repairs

HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface, they can act as a target for the incoming HTTP requests and can be called directly by using their file name in the URL.

http://www.carserviceautorepair.com/
European maintenance and repairs from brakes, tune ups, front end alignment to engine overhaul, we do it all.

Website SEO United States | Reply

Sunday, February 08, 2009 3:09 AM

Website SEO

Nice code development. Thanks for sharing..would like more on this topic..

Birch Tire and Auto Service United Kingdom | Reply

Tuesday, February 10, 2009 1:42 AM

Birch Tire and Auto Service

Including both client-side and server-side components, ASP.NET AJAX allows the developer to create web applications in ASP.NET 2.0 (and to a limited extent in other environments) which can update data on the web page without a complete reload of the page. The key technology which enables this functionality is the XMLHttpRequest object, along with Javascript and DHTML.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading