Common Tool Class 9-Upload thumbnail class

Source: Internet
Author: User
Tags bmp image

public class Thumbnail
{
Private Image srcimage;
private string Srcfilename;

<summary>
Create
</summary>
<param name= "FileName" > Original picture Path </param>
public bool SetImage (string FileName)
{
Srcfilename = Utils.getmappath (FileName);
Try
{
Srcimage = Image.FromFile (srcfilename);
}
Catch
{
return false;
}
return true;

}

<summary>
Callback
</summary>
<returns></returns>
public bool Thumbnailcallback ()
{
return false;
}

//<summary>
//Generate thumbnails, return image objects of thumbnails
//</summary>
//<param name= "width" > thumbnail width </param>
//<param name= "height" > thumbnail height </param>
///<returns> thumbnail Image Object </ Returns>
Public Image GetImage (int width,int Height)
{
image img;
Image.getthumbnailimageabort callb = new Image.getthumbnailimageabort (thumbnailcallback);
img = srcimage.getthumbnailimage (WIDTH,HEIGHT,CALLB, IntPtr.Zero);
return img;
}

//<summary>
//Save thumbnails
//</summary>
//<param name= "Width" ></PARAM>
// <param name= "Height" ></PARAM>
public void savethumbnailimage (int width,int Height)
{
Switch ( Path.getextension (Srcfilename). ToLower ())
{
case ". png":
SaveImage (Width, Height, imageformat.png);
Break
case ". gif":
SaveImage (Width, Height, imageformat.gif);
Break
Default:
SaveImage (Width, Height, imageformat.jpeg);
Break
}
}

<summary>
Generate thumbnails and save
</summary>
<param name= "width" > thumbnail widths </param>
<param name= "height" > Thumbnail Heights </param>
<param name= "Imgformat" > Saved image formats </param>
<returns> image objects for thumbnails </returns>
public void saveimage (int width,int Height, imageformat Imgformat)
{
if (Imgformat! = imageformat.gif && (srcimage.width > Width) | | (Srcimage.height > Height))
{
Image img;
Image.getthumbnailimageabort callb = new Image.getthumbnailimageabort (thumbnailcallback);
img = Srcimage.getthumbnailimage (Width, Height, CALLB, IntPtr.Zero);
Srcimage.dispose ();
Img. Save (Srcfilename, Imgformat);
Img. Dispose ();
}
}

#region Helper

//<summary>
//Save picture
//</summary>
//<param name= "image" >image object </param>
//<param name= "Savepath" > Save path </param>
//<param name= "ici" > Codec parameters in the specified format </param>
private static void SaveImage (image image, String savepath, ImageCodecInfo ici)
{
//Set Encoderparameter of the original picture object S object
EncoderParameters parameters = new EncoderParameters (1);
Parameters. Param[0] = new Encoderparameter (Encoder.quality, ((long) 100));
Image. Save (Savepath, ICI, parameters);
Parameters. Dispose ();
}

//<summary>
//obtain all relevant information about the image codec
//</summary>
//<param name= "MimeType" > A string </param> that contains the codec's Multipurpose Internet Mail Extension Protocol (MIME) type;
//<returns> returns all relevant information about the image codec </returns>
Private Static ImageCodecInfo Getcodecinfo (string mimeType)
{
imagecodecinfo[] Codecinfo = Imagecodecinfo.getimageencoders ();
foreach (ImageCodecInfo ici in codecinfo)
{
if (ici. MimeType = = MimeType)
return ici;
}
return null;
}

//<summary>
//Calculate new size
//</summary>
//<param name= "width" > Original width </param>
<param name= "Height" > Original height </param>
//<param name= "MaxWidth" > Max new width </param>
// <param name= "MaxHeight" > Maximum new height </param>
//<returns></returns>
private static Size Resizeimage (int width, int height, int maxWidth, int maxheight)
{

if (maxWidth <= 0)
MaxWidth = width; if (maxheight <= 0)
MaxHeight = height;
//Above 2012-02-05 modified =================
Decimal max_width = (decimal) MaxWidth;
Decimal max_height = (decimal) maxheight;
Decimal aspect_ratio = max_width/max_height;

int newwidth, newheight;
Decimal originalwidth = (decimal) width;
Decimal originalheight = (decimal) height;

if (originalwidth > Max_width | | originalheight > Max_height)
{
decimal factor;
Determine the largest factor
if (Originalwidth/originalheight > Aspect_ratio)
{
factor = OriginalWidth /max_width;
Newwidth = Convert.ToInt32 (originalwidth/factor);
Newheight = Convert.ToInt32 (originalheight/factor);
}
Else
{
factor = originalheight/max_height;
Newwidth = Convert.ToInt32 (originalwidth/factor);
Newheight = Convert.ToInt32 (originalheight/factor);
}
}
Else
{
Newwidth = width;
Newheight = height;
}
return new Size (newwidth,newheight);
}

//<summary>
//Get Picture format
//</summary>
//<param name= "name" > file name </param>
<returns></returns>
public static ImageFormat GetFormat (string name)
{
String ext = name. Substring (name. LastIndexOf (".") + 1);
Switch (ext. ToLower ())
{
case ' jpg ':
case ' JPEG ':
return imageformat.jpeg;
case ' bmp ':
return imageformat.bmp ;
Case "PNG":
return imageformat.png,
case "gif":
return imageformat.gif;
Default:
return imagefor Mat. Jpeg;
}
}
#endregion

<summary>
Making small Squares
</summary>
<param name= "image" > Picture objects </param>
<param name= "NewFileName" > New address </param>
<param name= "NewSize" > Length or Width </param>
public static void Makesquareimage (image image, String newfilename, int newSize)
{
int i = 0;
int width = image. Width;
int height = image. Height;
if (Width > height)
i = height;
Else
i = width;

Bitmap B = new Bitmap (newSize, newSize);

Try
{
Graphics g = graphics.fromimage (b);
Setting high-quality interpolation methods
G.interpolationmode = Interpolationmode.highqualitybicubic;
Set high quality, low speed rendering smoothness
G.smoothingmode = Smoothingmode.antialias;
G.pixeloffsetmode = pixeloffsetmode.highquality;
Clears the entire drawing surface and fills it with a transparent background color
G.clear (color.transparent);
if (Width < height)
G.drawimage (Image, new Rectangle (0, 0, newSize, newSize), new Rectangle (0, (height-width)/2, width, width), GraphicsUnit. Pixel);
Else
G.drawimage (Image, new Rectangle (0, 0, newSize, newSize), New Rectangle ((width-height)/2, 0, height, height), Graphicsuni T.pixel);

SaveImage (b, NewFileName, Getcodecinfo ("image/" + GetFormat (newfilename). ToString (). ToLower ()));
}
Finally
{
Image. Dispose ();
B.dispose ();
}
}

<summary>
Making small Squares
</summary>
<param name= "filename" > picture file name </param>
<param name= "NewFileName" > New address </param>
<param name= "NewSize" > Length or Width </param>
public static void Makesquareimage (String fileName, string newfilename, int newSize)
{
Makesquareimage (Image.FromFile (fileName), NewFileName, newSize);
}

<summary>
Making remote Small Squares
</summary>
<param name= "url" > Picture url</param>
<param name= "NewFileName" > New address </param>
<param name= "NewSize" > Length or Width </param>
public static void Makeremotesquareimage (string url, string newfilename, int newSize)
{
Stream stream = getremoteimage (URL);
if (stream = = null)
Return
Image original = Image.fromstream (stream);
Stream. Close ();
Makesquareimage (original, NewFileName, newSize);
}

<summary>
Make thumbnail images
</summary>
<param name= "original" > Picture objects </param>
<param name= "NewFileName" > New map Path </param>
<param name= "MaxWidth" > Max width </param>
<param name= "MaxHeight" > Maximum height </param>
public static void Makethumbnailimage (Image original, string newfilename, int maxWidth, int maxheight)
{
Size _newsize = Resizeimage (original. Width,original. Height,maxwidth, MaxHeight);

using (Image displayimage = new Bitmap (original, _newsize))
{
Try
{
Displayimage.save (NewFileName, original. Rawformat);
}
Finally
{
Original. Dispose ();
}
}
}

//<summary>
//Make thumbnails
//</summary>
//<param name= "filename" > file name </param>
//<param name= "NewFileName" > New map path </param>
//<param name= "MaxWidth" > Max width </param>
//<param name= "maxheight" > Maximum height </param>
public static void Makethumbnailimage (String fileName, string newfilename, int maxWidth, int maxheight)
{
//2012-02-05 modified, support replacement
byte[] Imagebytes = file.readallbytes (FileName);
Image img = image.fromstream (new System.IO.MemoryStream (imagebytes));
Makethumbnailimage (IMG, NewFileName, maxWidth, maxheight);
//Original text
//makethumbnailimage (Image.FromFile (fileName), NewFileName, MaxWidth, maxheight);
}

#region Image Thumbnail Generation method
<summary>
Generate thumbnail images
</summary>
<param name= "FileName" > Source map Path (absolute path) </param>
<param name= "NewFileName" > Thumbnail path (absolute path) </param>
<param name= "width" > Thumbnail width </param>
<param name= "height" > thumbnail height </param>
<param name= "mode" > How to Generate Thumbnails </param>
public static void Makethumbnailimage (String fileName, string newfilename, int width, int height, string mode)
{
Image originalimage = Image.FromFile (fileName);
int towidth = width;
int toheight = height;

int x = 0;
int y = 0;
int ow = Originalimage.width;
int oh = originalimage.height;

Switch (mode)
{
Case "HW"://Specifies aspect scaling (possibly deformed)
break;
Case "W"://Specify width, high proportionally
Toheight = Originalimage.hei Ght * WIDTH/ORIGINALIMAGE.WIDTH;
break;
Case "H"://Specify high, wide proportionally
Towidth = Originalimage.width * height/originalimage.height;
break;
Case "Cut"://Specify Aspect cut (not deformed)
if (double) originalimage.width/(double) originalimage.height > (double) towidth/(double) toheight) br> {
Oh = originalimage.height;
ow = Originalimage.height * towidth/toheight;
y = 0;
x = (originalimage . Width-ow)/2;
}
Else
{
ow = originalimage.width;
Oh = originalimage.width * height/towidth;
x = 0;
y = (o RIGINALIMAGE.HEIGHT-OH)/2;
}
Break,
Default:
break;
}

Create a new BMP image
Bitmap B = new Bitmap (towidth, toheight);
Try
{
Create a new artboard
Graphics g = graphics.fromimage (b);
Setting high-quality interpolation methods
G.interpolationmode = Interpolationmode.highqualitybicubic;
Set high quality, low speed rendering smoothness
G.smoothingmode = Smoothingmode.antialias;
G.pixeloffsetmode = pixeloffsetmode.highquality;
Empty the canvas and fill it with a transparent background color
G.clear (color.transparent);
Draws the specified portion of the original picture at the specified position and at the specified size
G.drawimage (Originalimage, New Rectangle (0, 0, Towidth, toheight), New Rectangle (x, Y, Ow, OH), graphicsunit.pixel);

SaveImage (b, NewFileName, Getcodecinfo ("image/" + GetFormat (newfilename). ToString (). ToLower ()));
}
catch (System.Exception e)
{
Throw e;
}
Finally
{
Originalimage.dispose ();
B.dispose ();
}
}
#endregion

#region Picture Clipping method
<summary>
Crop and save the picture
</summary>
<param name= "FileName" > Source map Path (absolute path) </param>
<param name= "NewFileName" > Thumbnail path (absolute path) </param>
<param name= "MaxWidth" > Thumbnail width </param>
<param name= "maxheight" > Thumbnail height </param>
<param name= "Cropwidth" > Clipping width </param>
<param name= "Cropheight" > Crop height </param>
<param name= "X" >x axis </param>
<param name= "Y" >y axis </param>
public static bool Makethumbnailimage (string fileName, string newfilename, int maxWidth, int maxheight, int cropwidth, int cropheight, int X, int Y)
{
byte[] imagebytes = file.readallbytes (fileName);
Image originalimage = Image.fromstream (new System.IO.MemoryStream (imagebytes));
Bitmap B = new Bitmap (cropwidth, cropheight);
Try
{
using (Graphics g = graphics.fromimage (b))
{
Setting high-quality interpolation methods
G.interpolationmode = Interpolationmode.highqualitybicubic;
Set high quality, low speed rendering smoothness
G.smoothingmode = Smoothingmode.antialias;
G.pixeloffsetmode = pixeloffsetmode.highquality;
Empty the canvas and fill it with a transparent background color
G.clear (color.transparent);
Draws the specified portion of the original picture at the specified position and at the specified size
G.drawimage (Originalimage, New Rectangle (0, 0, Cropwidth, cropheight), X, Y, Cropwidth, Cropheight, GraphicsUnit.Pixel);
Image displayimage = new Bitmap (b, MaxWidth, maxheight);
SaveImage (DisplayImage, NewFileName, Getcodecinfo ("image/" + GetFormat (newfilename). ToString (). ToLower ()));
return true;
}
}
catch (System.Exception e)
{
Throw e;
}
Finally
{
Originalimage.dispose ();
B.dispose ();
}
}
#endregion

//<summary>
//Make remote thumbnail
//</summary>
//<param name= "url" > Picture url</param>
//<param name= "NewFileName" > New map path </param>
//<param name= "MaxWidth" > Max width </param>
//<param name= "maxheight" > Maximum height </param>
public static void Makeremotethumbnailimage (string URL, string newfilename, int maxWidth, int maxheight)
{
Stream stream = getremoteimage (URL);
if (Stream = = null)
Return
Image original = Image.fromstream (stream);
Stream. Close ();
Makethumbnailimage (Original, NewFileName, MaxWidth, maxheight);
}

<summary>
Get picture Stream
</summary>
<param name= "url" > Picture url</param>
<returns></returns>
private static Stream getremoteimage (string url)
{
HttpWebRequest request = (HttpWebRequest) httpwebrequest.create (URL);
Request. Method = "GET";
Request. contentlength = 0;
Request. Timeout = 20000;
HttpWebResponse response = null;

Try
{
Response = (HttpWebResponse) request. GetResponse ();
return response. GetResponseStream ();
}
Catch
{
return null;
}
}
}

Common Tool Class 9-Upload thumbnail class

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.