473,725 Members | 2,232 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to reduce image file size?

Is there any routine I can call to reduce the size of an image file after
uploading a file from a client. I am looking to reduce file sizes
programmaticall y using C# in my web page after uploading. I know that
Photoshop can do it but I need to do it dynamically in my web page. I tried
doing it myself with some of the Bitmap thumbnail instructions but the
resulting image is very bad. I need a file reduction routine that creates a
good image that is smaller. I figured if Photoshop can do it then so can I
but how?
Apr 11 '06 #1
11 9573
Check out Bitmap.GetThumb nailImage

-Brock
http://staff.develop.com/ballen

Is there any routine I can call to reduce the size of an image file
after uploading a file from a client. I am looking to reduce file
sizes programmaticall y using C# in my web page after uploading. I know
that Photoshop can do it but I need to do it dynamically in my web
page. I tried doing it myself with some of the Bitmap thumbnail
instructions but the resulting image is very bad. I need a file
reduction routine that creates a good image that is smaller. I figured
if Photoshop can do it then so can I but how?

Apr 11 '06 #2
Brock;
Thanks for yur reply. I tried the Get ThumbnailImage function but the
resulting image is fuzzy. I reduced a 1360 X 2048 image to 272 X 408 and the
edges are blurry. I need something that gives me a better resolution.

"Brock Allen" wrote:
Check out Bitmap.GetThumb nailImage

-Brock
http://staff.develop.com/ballen

Is there any routine I can call to reduce the size of an image file
after uploading a file from a client. I am looking to reduce file
sizes programmaticall y using C# in my web page after uploading. I know
that Photoshop can do it but I need to do it dynamically in my web
page. I tried doing it myself with some of the Bitmap thumbnail
instructions but the resulting image is very bad. I need a file
reduction routine that creates a good image that is smaller. I figured
if Photoshop can do it then so can I but how?


Apr 12 '06 #3

"Parrot" <Pa****@discuss ions.microsoft. com> wrote in message
news:53******** *************** ***********@mic rosoft.com...
Brock;
Thanks for yur reply. I tried the Get ThumbnailImage function but the
resulting image is fuzzy. I reduced a 1360 X 2048 image to 272 X 408 and
the
edges are blurry. I need something that gives me a better resolution.

"Brock Allen" wrote:
Check out Bitmap.GetThumb nailImage


My first trys using GetThumbnailIma ge were very ugly, but this makes images
that look just fine:
-Fred
using System;

using System.Data;

using System.Configur ation;

using System.Web;

using System.Web.Secu rity;

using System.Web.UI;

using System.Web.UI.W ebControls;

using System.Web.UI.W ebControls.WebP arts;

using System.Web.UI.H tmlControls;

using System.IO;

using System.Drawing;

/// <summary>

/// Summary description for makeThumbnail

/// </summary>

public class makeThumbnail

{

public makeThumbnail(s tring parmFileIn, out int rc)

{

rc = 0;

string filePathSourceF ile = HttpContext.Cur rent.Server.Map Path("~/images/");

string filePathDestFil e =
HttpContext.Cur rent.Server.Map Path("~/thumbnails/");

string fullSourceFile = filePathSourceF ile + parmFileIn;

//string currentImageFil e;

//string thumbnailFile;

int thumbnailHeight ;

int thumbnailWidth;

int maxThumbSize = 150;

//int minThumbSize = 120; // 4 x 6 ratio

double hx; double wx;

// create an image object, using the filename we just retrieved

System.Drawing. Image sourceImage =
System.Drawing. Image.FromFile( fullSourceFile) ;

hx = sourceImage.Hei ght;

wx = sourceImage.Wid th;

// calc the thumbnail Width and Height: -scale to max with

if (sourceImage.Wi dth > sourceImage.Hei ght) // landscape: width is fixed,
scale height:

{

thumbnailWidth = maxThumbSize;

//thumbnailHeight = minThumbSize;

thumbnailHeight = Convert.ToInt32 ((hx / wx) * thumbnailWidth) ;

}

else // portrait: height is fixed at max, scale width:

{

thumbnailHeight = maxThumbSize;

thumbnailWidth = Convert.ToInt32 ((wx / hx) * thumbnailHeight );

}

System.Drawing. Image thumbnailImage =
sourceImage.Get ThumbnailImage( thumbnailWidth, thumbnailHeight , new
System.Drawing. Image.GetThumbn ailImageAbort(T humbnailCallbac k),
IntPtr.Zero);
// make a memory stream to work with the image bytes

MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream

thumbnailImage. Save(imageStrea m, System.Drawing. Imaging.ImageFo rmat.Jpeg);

string outfile = filePathDestFil e + parmFileIn;

try

{

thumbnailImage. Save(outfile);

rc = 77;

}

catch (Exception e)

{

rc = 27;

string dummy = e.ToString();

return;

}

}

/// <summary>

/// </summary>

/// <returns>true </returns>

public bool ThumbnailCallba ck()

{

return true;

}
}
Apr 12 '06 #4
Yeah, you need to do the math to scale properly.

-Brock
http://staff.develop.com/ballen

Brock;
Thanks for yur reply. I tried the Get ThumbnailImage function but the
resulting image is fuzzy. I reduced a 1360 X 2048 image to 272 X 408
and the
edges are blurry. I need something that gives me a better resolution.
"Brock Allen" wrote:
Check out Bitmap.GetThumb nailImage

-Brock
http://staff.develop.com/ballen
Is there any routine I can call to reduce the size of an image file
after uploading a file from a client. I am looking to reduce file
sizes programmaticall y using C# in my web page after uploading. I
know that Photoshop can do it but I need to do it dynamically in my
web page. I tried doing it myself with some of the Bitmap thumbnail
instructions but the resulting image is very bad. I need a file
reduction routine that creates a good image that is smaller. I
figured if Photoshop can do it then so can I but how?

Apr 12 '06 #5
Fred;
Thanks for your reply. I copied your coding and ran a test and it gave
similar results from my code in that any thumbnail having a size greater than
40K bytes shows a marked deterioration in quality. I guess since it is a
thumbnail routine, it is advisable to keep the resulting image at a thumbnail
size rather than just a reduction from the original image.
Dave Uphoff

"Fred Exley" wrote:

"Parrot" <Pa****@discuss ions.microsoft. com> wrote in message
news:53******** *************** ***********@mic rosoft.com...
Brock;
Thanks for yur reply. I tried the Get ThumbnailImage function but the
resulting image is fuzzy. I reduced a 1360 X 2048 image to 272 X 408 and
the
edges are blurry. I need something that gives me a better resolution.

"Brock Allen" wrote:
Check out Bitmap.GetThumb nailImage


My first trys using GetThumbnailIma ge were very ugly, but this makes images
that look just fine:
-Fred
using System;

using System.Data;

using System.Configur ation;

using System.Web;

using System.Web.Secu rity;

using System.Web.UI;

using System.Web.UI.W ebControls;

using System.Web.UI.W ebControls.WebP arts;

using System.Web.UI.H tmlControls;

using System.IO;

using System.Drawing;

/// <summary>

/// Summary description for makeThumbnail

/// </summary>

public class makeThumbnail

{

public makeThumbnail(s tring parmFileIn, out int rc)

{

rc = 0;

string filePathSourceF ile = HttpContext.Cur rent.Server.Map Path("~/images/");

string filePathDestFil e =
HttpContext.Cur rent.Server.Map Path("~/thumbnails/");

string fullSourceFile = filePathSourceF ile + parmFileIn;

//string currentImageFil e;

//string thumbnailFile;

int thumbnailHeight ;

int thumbnailWidth;

int maxThumbSize = 150;

//int minThumbSize = 120; // 4 x 6 ratio

double hx; double wx;

// create an image object, using the filename we just retrieved

System.Drawing. Image sourceImage =
System.Drawing. Image.FromFile( fullSourceFile) ;

hx = sourceImage.Hei ght;

wx = sourceImage.Wid th;

// calc the thumbnail Width and Height: -scale to max with

if (sourceImage.Wi dth > sourceImage.Hei ght) // landscape: width is fixed,
scale height:

{

thumbnailWidth = maxThumbSize;

//thumbnailHeight = minThumbSize;

thumbnailHeight = Convert.ToInt32 ((hx / wx) * thumbnailWidth) ;

}

else // portrait: height is fixed at max, scale width:

{

thumbnailHeight = maxThumbSize;

thumbnailWidth = Convert.ToInt32 ((wx / hx) * thumbnailHeight );

}

System.Drawing. Image thumbnailImage =
sourceImage.Get ThumbnailImage( thumbnailWidth, thumbnailHeight , new
System.Drawing. Image.GetThumbn ailImageAbort(T humbnailCallbac k),
IntPtr.Zero);
// make a memory stream to work with the image bytes

MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream

thumbnailImage. Save(imageStrea m, System.Drawing. Imaging.ImageFo rmat.Jpeg);

string outfile = filePathDestFil e + parmFileIn;

try

{

thumbnailImage. Save(outfile);

rc = 77;

}

catch (Exception e)

{

rc = 27;

string dummy = e.ToString();

return;

}

}

/// <summary>

/// </summary>

/// <returns>true </returns>

public bool ThumbnailCallba ck()

{

return true;

}
}

Apr 12 '06 #6
Actually, GetThumbNailIma ge is not the best solution at all. Here's a
ResizeImage method for a control I developed a year or so ago in Whidbey
beta. I have compiled it in the release version but haven't tested it. In
either case, it will show you how to use a Graphics object to resize your
image while maintaining high quality.

--
Dale Preston
MCAD C#
MCSE, MCDBA
"Parrot" wrote:
Is there any routine I can call to reduce the size of an image file after
uploading a file from a client. I am looking to reduce file sizes
programmaticall y using C# in my web page after uploading. I know that
Photoshop can do it but I need to do it dynamically in my web page. I tried
doing it myself with some of the Bitmap thumbnail instructions but the
resulting image is very bad. I need a file reduction routine that creates a
good image that is smaller. I figured if Photoshop can do it then so can I
but how?

Apr 13 '06 #7
Whoops. Here's the code:

private Image ResizeImage(Ima ge mg, Size newSize)
{
double ratio = 0d;
double myThumbWidth = 0d;
double myThumbHeight = 0d;
int x = 0;
int y = 0;

Bitmap bp;

if ((mg.Width / Convert.ToDoubl e(newSize.Width )) > (mg.Height /
Convert.ToDoubl e(newSize.Heigh t)))
ratio = Convert.ToDoubl e(mg.Width) / Convert.ToDoubl e(newSize.Width );
else
ratio = Convert.ToDoubl e(mg.Height) / Convert.ToDoubl e(newSize.Heigh t);
myThumbHeight = Math.Ceiling(mg .Height / ratio);
myThumbWidth = Math.Ceiling(mg .Width / ratio);
Size thumbSize = new Size((int)myThu mbWidth, (int)myThumbHei ght);
bp = new Bitmap(newSize. Width, newSize.Height) ;
x = (newSize.Width - thumbSize.Width ) / 2;
y = (newSize.Height - thumbSize.Heigh t);

Graphics g = Graphics.FromIm age(bp);
g.SmoothingMode = SmoothingMode.H ighQuality;
g.Interpolation Mode = InterpolationMo de.HighQualityB icubic;
g.PixelOffsetMo de = PixelOffsetMode .HighQuality;
Rectangle rect = new Rectangle(x, y, thumbSize.Width , thumbSize.Heigh t);
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pi xel);
return bp;
}

--
Dale Preston
MCAD C#
MCSE, MCDBA
"Parrot" wrote:
Is there any routine I can call to reduce the size of an image file after
uploading a file from a client. I am looking to reduce file sizes
programmaticall y using C# in my web page after uploading. I know that
Photoshop can do it but I need to do it dynamically in my web page. I tried
doing it myself with some of the Bitmap thumbnail instructions but the
resulting image is very bad. I need a file reduction routine that creates a
good image that is smaller. I figured if Photoshop can do it then so can I
but how?

Apr 13 '06 #8
Dale;
Thank you for your reply. Can this code only work in ASPNET 2.0? I get
compile errors trying it in 1.1 because it doesn't recognize the Graphics
class for Web forms and I don't know what the Namespace is?
Dave Uphoff

"Dale" wrote:
Actually, GetThumbNailIma ge is not the best solution at all. Here's a
ResizeImage method for a control I developed a year or so ago in Whidbey
beta. I have compiled it in the release version but haven't tested it. In
either case, it will show you how to use a Graphics object to resize your
image while maintaining high quality.

--
Dale Preston
MCAD C#
MCSE, MCDBA
"Parrot" wrote:
Is there any routine I can call to reduce the size of an image file after
uploading a file from a client. I am looking to reduce file sizes
programmaticall y using C# in my web page after uploading. I know that
Photoshop can do it but I need to do it dynamically in my web page. I tried
doing it myself with some of the Bitmap thumbnail instructions but the
resulting image is very bad. I need a file reduction routine that creates a
good image that is smaller. I figured if Photoshop can do it then so can I
but how?

Apr 13 '06 #9
Dale;
Just to let you know that I got your routine to work and it does create a
sharp image even though the file size is reduced. I want to thank you very
much for giving me a valuable tool for web programming. I did have to make
some changes to make it work in ASPNET 1.1. I needed to add the Namespace
System.Drawing. Drawing2D. I also made a few other changes to make it work
for me which I have highlighted in the code below. The routine reduced a
650KB image file to a 14.7 KB file with 250 X 400 dimension and the clarity
is intact just like in Photoshop. Thanks again.
Dave Uphoff

Here is the calling routine:

Bitmap mg = new Bitmap("c:\\sca npics\\animals\ \cats\\midnite1 .jpg");

Size newSize = new Size(250, 400);

Bitmap bp = ResizeImage(mg, newSize);

bp.Save("c:\\in etpub\\wwwroot\ \warmfrag\\pics \\myimage.jpg", System.Drawing. Imaging.ImageFo rmat.Jpeg);
--------------------------------------------------------------------

And here is the routine itself.
------------------------------------------------------------------

private Bitmap ResizeImage(Bit map mg, Size newSize)
{
double ratio = 0d;
double myThumbWidth = 0d;
double myThumbHeight = 0d;
int x = 0;
int y = 0;

Bitmap bp;
if ((mg.Width / Convert.ToDoubl e(newSize.Width )) > (mg.Height /
Convert.ToDoubl e(newSize.Heigh t)))
ratio = Convert.ToDoubl e(mg.Width) / Convert.ToDoubl e(newSize.Width );
else
ratio = Convert.ToDoubl e(mg.Height) / Convert.ToDoubl e(newSize.Heigh t);
myThumbHeight = Math.Ceiling(mg .Height / ratio);
myThumbWidth = Math.Ceiling(mg .Width / ratio);

Size thumbSize = new Size((int)myThu mbWidth, (int)myThumbHei ght);
bp = new Bitmap(newSize. Width, newSize.Height) ;
x = (newSize.Width - thumbSize.Width ) / 2;
y = (newSize.Height - thumbSize.Heigh t);
// Had to add System.Drawing class in front of Graphics ---
System.Drawing. Graphics g = Graphics.FromIm age(bp);
g.SmoothingMode = SmoothingMode.H ighQuality;
g.Interpolation Mode = InterpolationMo de.HighQualityB icubic;
g.PixelOffsetMo de = PixelOffsetMode .HighQuality;
Rectangle rect = new Rectangle(x, y, thumbSize.Width , thumbSize.Heigh t);
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pi xel);

return bp;
}

"Dale" wrote:
Whoops. Here's the code:

private Image ResizeImage(Ima ge mg, Size newSize)
{
double ratio = 0d;
double myThumbWidth = 0d;
double myThumbHeight = 0d;
int x = 0;
int y = 0;

Bitmap bp;

if ((mg.Width / Convert.ToDoubl e(newSize.Width )) > (mg.Height /
Convert.ToDoubl e(newSize.Heigh t)))
ratio = Convert.ToDoubl e(mg.Width) / Convert.ToDoubl e(newSize.Width );
else
ratio = Convert.ToDoubl e(mg.Height) / Convert.ToDoubl e(newSize.Heigh t);
myThumbHeight = Math.Ceiling(mg .Height / ratio);
myThumbWidth = Math.Ceiling(mg .Width / ratio);
Size thumbSize = new Size((int)myThu mbWidth, (int)myThumbHei ght);
bp = new Bitmap(newSize. Width, newSize.Height) ;
x = (newSize.Width - thumbSize.Width ) / 2;
y = (newSize.Height - thumbSize.Heigh t);

Graphics g = Graphics.FromIm age(bp);
g.SmoothingMode = SmoothingMode.H ighQuality;
g.Interpolation Mode = InterpolationMo de.HighQualityB icubic;
g.PixelOffsetMo de = PixelOffsetMode .HighQuality;
Rectangle rect = new Rectangle(x, y, thumbSize.Width , thumbSize.Heigh t);
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pi xel);
return bp;
}

--
Dale Preston
MCAD C#
MCSE, MCDBA
"Parrot" wrote:
Is there any routine I can call to reduce the size of an image file after
uploading a file from a client. I am looking to reduce file sizes
programmaticall y using C# in my web page after uploading. I know that
Photoshop can do it but I need to do it dynamically in my web page. I tried
doing it myself with some of the Bitmap thumbnail instructions but the
resulting image is very bad. I need a file reduction routine that creates a
good image that is smaller. I figured if Photoshop can do it then so can I
but how?

Apr 13 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5532
by: André Næss | last post by:
Photoshop has a function called optimize to file size which tries to fit an image to some given file size. Because I need to make sure no images on a site I'm working on are larger than X KB I need something similar so that users don't have to worry so much about image file size. Does anyone know of a way to do this, preferably using ImageMagick or GD? Doing several calls to ImageMagick with different optimize settings is a not a good...
14
16427
by: Peter CCH | last post by:
Database log of my DB is around 2GB. The database is using FULL recovery option. I want to reduce the file size of the log cause it takes up a lot of space. I'd do a full database backup, then backup the transaction log as well .... both backup performed with a check on the option "clear inactive entries from transaction log".
12
695
by: Ken | last post by:
How can I determine a image file size before uploading it? I would like to make sure the size is under a maximum before taking the time to upload it. If I have to upload the file before determining the size, it could take a few minutes (Mbs) on a slow connection before I can determine if the size is too large. Thanks!
5
13738
by: Wazz Up | last post by:
Is there a way to read the file size of images with JavaScript ? I know how to read the width and height. Later, Art.
3
2994
by: Parrot | last post by:
Is there any routine I can call to reduce the size of an image file after uploading a file from a client. I am looking to reduce file sizes programmatically using C# in my web page after uploading. I know that Photoshop can do it but I need to do it dynamically in my web page. I tried doing it myself with some of the Bitmap thumbnail instructions but the resulting image is very bad. I need a file reduction routine that creates a good...
2
3400
by: demo | last post by:
I am new to forums, I would like to know how to find a bmp or jpg image file size before loading it into my database. Hope you can help Demo.
4
2596
by: C Mann | last post by:
How can I reduce the size of the HTML output produced by Visual Studio 2005 ASP.NET controls. I have some pages that are 500 - 750kb. I thought that viewstate would be to blame but the worst of it is code like this. <a class="ctl00_ContentPlaceHolder1_tabSubject__ctl0_tvSubject_0 ctl00_ContentPlaceHolder1_tabSubject__ctl0_tvSubject_1"
1
3431
by: ShailendraPune | last post by:
I have one db test with one .mdf and .ldf file. ..mdf file size is 100mb and for some reson i removed all the tables from that .mdf file and transfer it into new secondary file so all the tables moved into secondary file now i want to reduce the first .mdf file from 100 mb to 50mb is that possible,it's showing 90mb is free. Please reply
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.