473,574 Members | 2,337 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Resizing a jpg then saving it

I'm unfamiliar with image manipulation using c#.

How can i resize a jpg that currently exists in a file and save it resized
as a new file.
The examples i've found have been a bit misleading for my particular
requirements.
Nov 17 '05 #1
4 4243
Take a look at http://www.codeproject.com/csharp/imageresize.asp for some
pretty good example code on how to do that.

Brendan Grant

"CodeRazor" wrote:
I'm unfamiliar with image manipulation using c#.

How can i resize a jpg that currently exists in a file and save it resized
as a new file.
The examples i've found have been a bit misleading for my particular
requirements.

Nov 17 '05 #2
use GDIPlus.DLL routines...

"CodeRazor" wrote:
I'm unfamiliar with image manipulation using c#.

How can i resize a jpg that currently exists in a file and save it resized
as a new file.
The examples i've found have been a bit misleading for my particular
requirements.

Nov 17 '05 #3

I'm going to do something I shouldn't do now - past massive amounts of code into a
newsgroup message.

This is some code that I wrote, begged, borrowed or just plain plagerised from arround
the internet. It's a bit of a hotch-potch and there must be a THOUSAND better ways to
do it. It sometimes doesn't work and the images may be wonky... but that's because I
wrote it while half asleep.

Copy and paste it into a notepad or something before you try and read it. It is designed
to work with an aspx page so you may need to tweak bits.

While we're on the subject I'll take any advice as to how to make this
better/faster/safer.

--- CODE BEGINS ---

using System;
using System.IO;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
using System.Drawing. Drawing2D;
namespace Adquiesco2
{
public class Thumbnail : PageBase
{
protected override void Page_Load(objec t sender,
System.EventArg s e)
{
// get the file name
string file = Request.QuerySt ring["file"];
string id = Request.QuerySt ring["id"];
string scaleStr = Request.QuerySt ring["scale"];
string mode = Request.QuerySt ring["mode"];
System.Drawing. Image image = null;

if (file == null)
{
if (id==null)
{

Response.Redire ct(@"RenderFont .aspx?text=Inva lid%20Image", true);
}
else
{
object imagePath =
ExecuteSqlScala r("SELECT fileName FROM Images WHERE imageId = " + id);
if (imagePath == null)

Response.Redire ct(@"RenderFont .aspx?text=Inva lid%20Id", true);
else
try
{
image =
System.Drawing. Image.FromFile( Server.MapPath( (string)(@"Imag es\Products\" +
imagePath)));
}
catch (IOException ioEx)
{

Response.Redire ct(@"RenderFont .aspx?text=File %20Not%20Found" , true);

Console.WriteLi ne(ioEx.StackTr ace);
}
}
}
else
{
try
{
image =
System.Drawing. Image.FromFile( Server.MapPath( file));
}
catch (IOException ioEx)
{

Response.Redire ct(@"RenderFont .aspx?text=File %20Not%20Found" , true);

Console.WriteLi ne(ioEx.StackTr ace);
}
}
if (scaleStr == null)
{
// Just stream the origional image

MemoryStream imageStream = new
MemoryStream();

// put the image into the memory stream
image.Save(imag eStream, image.RawFormat );
// make byte array the same size as the
image
byte[] imageContent = new
Byte[imageStream.Len gth];

// rewind the memory stream
imageStream.Pos ition = 0;

// load the byte array with the image
imageStream.Rea d(imageContent, 0,
(int)imageStrea m.Length);

// return byte array to caller with image type
if (image.RawForma t ==
System.Drawing. Imaging.ImageFo rmat.Gif)
Response.Conten tType =
"image/gif";
else if (image.RawForma t ==
System.Drawing. Imaging.ImageFo rmat.Jpeg)
Response.Conten tType = "image/jpeg";
else
Response.Conten tType = "image";
Response.Binary Write(imageCont ent);
imageStream.Clo se();
image.Dispose() ;
}
else
{
// create an image object, using the filename
we just retrieved
int scale = int.Parse(scale Str);

System.Drawing. Image newImage = null;

if (mode.ToLower() == "w")
{
newImage =
ScaleByStaticWi dth(image, scale);
}
else if (mode.ToLower() == "h")
{
newImage =
ScaleByStaticHe ight(image, scale);
}
else
{
newImage =
ScaleByPercent( image, scale);
}

// My sisters telephone number is : 07710 797
345
// make a memory stream to work with the
image bytes
MemoryStream imageStream = new
MemoryStream();

// put the image into the memory stream
newImage.Save(i mageStream,
System.Drawing. Imaging.ImageFo rmat.Jpeg);

// make byte array the same size as the
image
byte[] imageContent = new
Byte[imageStream.Len gth];

// rewind the memory stream
imageStream.Pos ition = 0;

// load the byte array with the image
imageStream.Rea d(imageContent, 0,
(int)imageStrea m.Length);

// return byte array to caller with image type
Response.Conten tType = "image/jpeg";
Response.Binary Write(imageCont ent);
newImage.Dispos e();
imageStream.Clo se();
}

}

/// <summary>
/// Required, but not used
/// </summary>
/// <returns>true </returns>
public bool ThumbnailCallba ck()
{
return true;
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET
Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new
System.EventHan dler(this.Page_ Load);
}
#endregion

// Image manipulation procedures

static private System.Drawing. Image
ScaleByPercent( System.Drawing. Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent/100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height ;

int destWidth = (int)(sourceWid th * nPercent);
int destHeight = (int)(sourceHei ght * nPercent);

return ScaleImage(imgP hoto, destWidth, destHeight);
}

static private System.Drawing. Image
ScaleByStaticWi dth(System.Draw ing.Image imgPhoto, int width)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height ;

int destWidth = width;
int destHeight = (int)(((double) (width)/sourceWidth) *
sourceHeight);

return ScaleImage(imgP hoto, destWidth, destHeight);
}

static private System.Drawing. Image
ScaleByStaticHe ight(System.Dra wing.Image imgPhoto, int height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height ;

int destWidth = (int)(((double) (height)/sourceHeight) *
sourceWidth);
int destHeight = height;

return ScaleImage(imgP hoto, destWidth, destHeight);
}
static private System.Drawing. Image
ScaleImage(Syst em.Drawing.Imag e imgPhoto, int height, int width)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height ;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = width;
int destHeight = height;

// Bitmap bmPhoto = new Bitmap(destWidt h,
destHeight, System.Drawing. Imaging.PixelFo rmat.Format24bp pRgb);

Bitmap bmPhoto = new Bitmap(destWidt h, destHeight,
System.Drawing. Imaging.PixelFo rmat.Format32bp pRgb);

bmPhoto.SetReso lution(imgPhoto .HorizontalReso lution,
imgPhoto.Vertic alResolution);

Graphics grPhoto = Graphics.FromIm age(bmPhoto);
grPhoto.Clear(S ystem.Drawing.C olor.White);
grPhoto.Interpo lationMode =
InterpolationMo de.HighQualityB icubic;

grPhoto.DrawIma ge(imgPhoto,
new
Rectangle(destX ,destY,destWidt h,destHeight),
new
Rectangle(sourc eX,sourceY,sour ceWidth,sourceH eight),
GraphicsUnit.Pi xel);

grPhoto.Dispose ();
return bmPhoto;
}
}

}

--- CODE ENDS ---
------------------------------------

Another unchecked rambeling brought to you by:

Oddball
joshua@bf#N0SP4 M#wd.co.uk
Nov 17 '05 #4
thank you for everyones comments, and suggestions.

CR
Nov 17 '05 #5

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

Similar topics

1
2004
by: adolph | last post by:
Using Access2000, I would like to resize an image then save it to a new file with the resized size. I'm taking pictures (JPGs) with my digitial set at 3.2 megs. I've figured out how to get my access program to find the pictures and show them as thumbnails so I can add a description and notes. I then rename and save these pictures to a...
0
1157
by: E | last post by:
I wrote code which Resizes images and then saves them below is the 2 methods. The problem is that half of the resized image turns out gray, as if it wasn't completed. Could someone please tell me what could be the problem? I have pasted code below. Also this is a link to sample image that has the problem...
4
19084
by: funcSter | last post by:
Hey, got a prob which is driving me nuts! I'm trying to resize the resolution of an image as well as it's pyhsical byte size. I've got: byte bytImage = null; System.Drawing.Image imgImage = null; System.Drawing.Image imgNewImage = null;
11
17827
by: Sharon | last post by:
I'm writing a new control derived from UserControl. I need to get an event when the control is done resizing. I tried the Resize, SizeChanged, Move and the Layout events and I also tried to override them. But they all invoked when the control is in the middle of the resizing process. I'm not using breakpoints, I'm using trace to see which...
1
2117
by: Ron Vecchi | last post by:
I am using asp.net to upload an image and then perform resizing on it and saving the different sizes to file. The resized images were coming up and being displayed in the bowser fine but the image sizes are a lot bigger(in file size) than the actual image being uploaded. The actual image being uploaded was around 22000bytes The smaller...
6
1922
by: neverstill | last post by:
hi- So I wrote this nice little page that will allow the managers to add images to the products table. Without too many details to confuse everything, basically what I'm doing is: getting an Image from there I'm creating a new Bitmap(Image, int w, int h); then I'm saving that bitmap various encoder quality values.
2
3986
by: Brad | last post by:
I have code which takes an image, uploaded from a web page, and saves it to a database. Now I want to always resize an uploaded image before it is saved to the database. My code to resize is below and of course it's not working properly because my web page which displays the resulting image from the database is not showing the image. I...
5
8512
by: drum118 | last post by:
Trying to resize a photo to use it as a background and it fails under part of the css <img src="subway/IMG_0730.JPG" width="3264" height="2448" alt="" /> I have try and the photo does not display <link rel="STYLESHEET" type="text/css" href="../../css/ttc.css"> <style type="text/css"> <!-- body {color: #4d9999;background-image:...
9
5285
by: dli07 | last post by:
Hello, I'm trying to convert a piece of code that creates a dynamic vertical resizing bar in a table from internet explorer to firefox. It's based on a post from http://blogs.crankygoblin.com/blogs/geoff.appleby/pages/50712.aspx. I've also read the post on this topic by bggraphics, but he doesn't arrive at a final result. The main problem I...
10
7051
by: mishrarajesh44 | last post by:
hii all, I am facing a problem currently.. i have a script for image uploading and resizing.. the image uploading takes place properly for every size images.. but, the resizing works for only small sized iamages.. for eg. resizing takes place for 70 kb sized images but fails for 600kb or more.. my code is below..
0
7828
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...
0
8089
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. ...
0
8127
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6493
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...
1
5638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5329
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...
0
3765
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3783
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1092
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...

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.