This article introduces a program code for generating a fixed proportion of image size in asp.net. For more information, see.
| The Code is as follows: |
Copy code |
/// <Summary> /// Compress the image /// </Summary> /// <Returns> </returns> Public string ResizePic () { # Region Compression Image start Bool IsImgFile = true; // determines whether it is an image file. String filePathName = "123"; // file storage path (Folder name) String fileName = "a.jpg"; // Original Name of the uploaded file String fileSysName = DateTime. Now. ToString ("yyyyMMddHHmmssfff") + "_" + fileName; // modified file name String filePath = ""; // file path String strImgPath = "/fileupload/"; // upload path If (IsImgFile) { Int maxWidth = 600; // maximum Image Width Int maxHeight = 400; // maximum Image Height System. Drawing. Image imgPhoto = System. Drawing. Image. FromFile (Server. MapPath (strImgPath) + filePathName + "/" + fileSysName ); Int imgWidth = imgPhoto. Width; Int imgHeight = imgPhoto. Height; If (imgWidth> imgHeight) // if the width exceeds the height, the compression is based on the width. { If (imgWidth> maxWidth) // if the image width exceeds the limit { Float toImgWidth = maxWidth; // The width of the compressed image. Float toImgHeight = imgHeight/(float) (imgWidth/toImgWidth); // The height of the image after compression System. Drawing. Bitmap img = new System. Drawing. Bitmap (imgPhoto, Int. Parse (toImgWidth. ToString ()), Int. Parse (toImgHeight. ToString ())); String strResizePicName = Server. MapPath (strImgPath) + filePathName + "/_ small _" + fileSysName; Img. Save (strResizePicName); // Save the compressed image FilePath = strImgPath + filePathName + "/_ small _" + fileSysName; // return the compressed image path. } } Else { If (imgHeight> maxHeight) { Float toImgHeight1 = maxHeight; Float toImgWidth1 = imgWidth/(float) (imgHeight/toImgHeight1 ); System. Drawing. Bitmap img = new System. Drawing. Bitmap (imgPhoto, Int. Parse (toImgWidth1.ToString ()), Int. Parse (toImgHeight1.ToString ())); String strResizePicName = Server. MapPath (strImgPath) + filePathName + "/_ small _" + fileSysName; Img. Save (strResizePicName ); FilePath = strImgPath + filePathName + "/_ small _" + fileSysName; } } } Return filePath; # Endregion } |