public static void Change()
 {
     Bitmap myBitmap;
     ImageCodecInfo myImageCodecInfo;
     Encoder myEncoder;
     EncoderParameter myEncoderParameter;
     EncoderParameters myEncoderParameters;
     // Create a Bitmap object based on a BMP file.
     myBitmap = new Bitmap(@"D:\Shapes.jpg");
     // Get an ImageCodecInfo object that represents the JPEG codec.
     myImageCodecInfo = GetEncoderInfo("image/jpeg");
     // Create an Encoder object based on the GUID
     // for the Quality parameter category.
     myEncoder = Encoder.Quality;
     // Create an EncoderParameters object.
     // An EncoderParameters object has an array of EncoderParameter
     // objects. In this case, there is only one
     // EncoderParameter object in the array.
     myEncoderParameters = new EncoderParameters(1);
     // Save the bitmap as a JPEG file with quality level 25.
     myEncoderParameter = new EncoderParameter(myEncoder, 25L);
     myEncoderParameters.Param[0] = myEncoderParameter;
     myBitmap.Save(@"c:\temp.jpg", myImageCodecInfo, myEncoderParameters);
     Byte[] bytes = File.ReadAllBytes(@"c:\temp.jpg");
     // Save the bitmap as a JPEG file with quality level 50.
     //myEncoderParameter = new EncoderParameter(myEncoder, 50L);
     //myEncoderParameters.Param[0] = myEncoderParameter;
     //myBitmap.Save(@"D:\Shapes050.jpg", myImageCodecInfo, myEncoderParameters);
     //// Save the bitmap as a JPEG file with quality level 75.
     //myEncoderParameter = new EncoderParameter(myEncoder, 75L);
     //myEncoderParameters.Param[0] = myEncoderParameter;
     //myBitmap.Save(@"D:\Shapes075.jpg", myImageCodecInfo, myEncoderParameters);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["width"] != null && Request.Form["width"] != String.Empty)
        {
            // image dimensions
            int width = Int32.Parse((Request.Form["width"].IndexOf('.') != -1) ? Request.Form["width"].Substring(0, Request.Form["width"].IndexOf('.')) : Request.Form["width"]);
            int height = Int32.Parse((Request.Form["height"].IndexOf('.') != -1) ? Request.Form["height"].Substring(0, Request.Form["height"].IndexOf('.')) : Request.Form["height"]);

            // image
            Bitmap result = new Bitmap(width, height);

            // set pixel colors
            for (int y = 0; y < height; y++)
            {
                // column counter for the row
                int x = 0;
                // get current row data
                string[] row = Request.Form["r" + y].Split(new char[]{','});
                // set pixels in the row
                for (int c = 0; c < row.Length; c++)
                {
                    // get pixel color and repeat count
                    string[] pixel = row[c].Split(new char[] { ':' });
                    Color current_color = ColorTranslator.FromHtml("#" + pixel[0]);
                    int repeat = pixel.Length > 1 ? Int32.Parse(pixel[1]) : 1;

                    // set pixel(s)
                    for (int l = 0; l < repeat; l++)
                    {
                        result.SetPixel(x, y, current_color);
                        x++;
                    }
                }
            }

            // output image

            // image type
            Response.ContentType = "image/jpeg";

            // find image encoder for selected type
            ImageCodecInfo[] encoders;
            ImageCodecInfo img_encoder = null;
            encoders = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codec in encoders)
                if (codec.MimeType == Response.ContentType)
                {
                    img_encoder = codec;
                    break;
                }

            // image parameters
            EncoderParameter jpeg_quality = new EncoderParameter(Encoder.Quality, 100L); // for jpeg images only
            EncoderParameters enc_params = new EncoderParameters(1);
            enc_params.Param[0] = jpeg_quality;

            result.Save(Response.OutputStream, img_encoder, enc_params);
        }
    }
    public void Page_Load(Object sender, EventArgs e) {		
		try{
			//Get the width and height from form
			width = Int32.Parse(Request["width"]);
			height = Int32.Parse(Request["height"]);		
		}catch(Exception ex){
			//If the width and height has not been given, we cannot create the image.
			Response.Write("Image width and height not provided.");
			Response.End();
		}
		//Background color, request and set default
		bgcolor = Request["bgcolor"];
		if (bgcolor=="" || bgcolor==null){
			bgcolor = "FFFFFF";
		}
		//Conver the bg color in ASP.NET format
		bgColor = ColorTranslator.FromHtml("#" + bgcolor);
		
		//Decompress the data
		//data = decompress(Request["data"]);		
		data = (Request["data"]);		
		
		//Parse data 
		rows = new String[height+1];
		rows = data.Split(';');
		
		//Build the image now
		buildBitmap();
		
		//Output it now
		Response.ContentType = "image/jpeg";		
		Response.AddHeader("Content-Disposition", "attachment; filename=\"FusionCharts.jpg\"");
		
		//Now, we need to encode the image using an encoder.
		//Find the encoder.
		ImageCodecInfo[] encoders;
		ImageCodecInfo img_encoder = null;
		encoders = ImageCodecInfo.GetImageEncoders();
		foreach (ImageCodecInfo codec in encoders){
			if (codec.MimeType == Response.ContentType){
				img_encoder = codec;
				break;
			}
		}
		//Set the quality as 100
		EncoderParameter jpeg_quality = new EncoderParameter(Encoder.Quality, 100L);
		EncoderParameters enc_params = new EncoderParameters(1);
		//Convey the parameter
		enc_params.Param[0] = jpeg_quality;
		
		//Save to output stream after applying proper encoders
		chart.Save(Response.OutputStream, img_encoder, enc_params);		
		
		//Dispose the bitmap
		gr.Dispose();
		chart.Dispose();						
    }
    public static void SaveJpeg(string path, Image image, int quality)
    {
        if ((quality < 0) || (quality > 100))
            {
                string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
                throw new ArgumentOutOfRangeException(error);
            }

            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            image.Save(path, jpegCodec, encoderParams);
    }
    public static void SaveJpeg(string path, System.Drawing.Image img, int quality, string typeS)
    {
        if (quality < 0 || quality > 100)
            throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");

        // Encoder parameter for image quality
        EncoderParameter qualityParam =
            new EncoderParameter(Encoder.Quality, quality);
        // Jpeg image codec
        ImageCodecInfo jpegCodec = GetEncoderInfo(typeS);

        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;

        img.Save(path, jpegCodec, encoderParams);
    }
Beispiel #6
0
    public static Stream SaveAsJpeg(this Image img, int quality = 90)
    {
        MemoryStream ms = new MemoryStream();
        ImageCodecInfo myImageCodecInfo;
        System.Drawing.Imaging.Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;

        myImageCodecInfo = GetEncoderInfo("image/jpeg");

        myEncoder = System.Drawing.Imaging.Encoder.Quality;
        myEncoderParameters = new EncoderParameters(1);

        myEncoderParameter = new EncoderParameter(myEncoder, quality);
        myEncoderParameters.Param[0] = myEncoderParameter;

        img.Save(ms, myImageCodecInfo, myEncoderParameters);

        return ms;
    }
    /// <summary>
    /// Method to resize, convert and save the image.
    /// </summary>
    /// <param name="image">Bitmap image.</param>
    /// <param name="maxWidth">resize width.</param>
    /// <param name="maxHeight">resize height.</param>
    /// <param name="quality">quality setting value.</param>
    /// <param name="filePath">file path.</param>      
    public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
    {
        // Get the image's original width and height
        int originalWidth = image.Width;
        int originalHeight = image.Height;

        // To preserve the aspect ratio
        float ratioX = (float)maxWidth / (float)originalWidth;
        float ratioY = (float)maxHeight / (float)originalHeight;
        float ratio = Math.Min(ratioX, ratioY);

        // New width and height based on aspect ratio
        int newWidth = (int)(originalWidth * ratio);
        int newHeight = (int)(originalHeight * ratio);

        // Convert other formats (including CMYK) to RGB.
        Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

        // Draws the image in the specified size with quality mode set to HighQuality
        using (Graphics graphics = Graphics.FromImage(newImage))
        {
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.DrawImage(image, 0, 0, newWidth, newHeight);
        }

        // Get an ImageCodecInfo object that represents the JPEG codec.
        ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

        // Create an Encoder object for the Quality parameter.
        Encoder encoder = Encoder.Quality;

        // Create an EncoderParameters object.
        EncoderParameters encoderParameters = new EncoderParameters(1);

        // Save the image as a JPEG file with quality level.
        EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
        encoderParameters.Param[0] = encoderParameter;
        newImage.Save(filePath, imageCodecInfo, encoderParameters);
    }
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="quality">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, byte quality = 90, int size = 1024, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            var firstFileInfo = new FileInfo(sFile);

            if (sfsc && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return(true);
            }

            using Image iSource = Image.FromFile(sFile);
            int dHeight = iSource.Height;
            int dWidth = iSource.Width;
            int sW, sH;

            //按比例缩放
            Size temSize = new Size(iSource.Width, iSource.Height);

            if (temSize.Width > dHeight || temSize.Width > dWidth)
            {
                if (temSize.Width * dHeight > temSize.Width * dWidth)
                {
                    sW = dWidth;
                    sH = dWidth * temSize.Height / temSize.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = temSize.Width * dHeight / temSize.Height;
                }
            }
            else
            {
                sW = temSize.Width;
                sH = temSize.Height;
            }

            using Bitmap bmpp = new Bitmap(dWidth, dHeight);
            using Graphics g  = Graphics.FromImage(bmpp);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            //以下代码为保存图片时,设置压缩质量
            using var ep     = new EncoderParameters();
            using var eParam = new EncoderParameter(Encoder.Quality, new long[] { quality });
            ep.Param[0]      = eParam;
            try
            {
                ImageCodecInfo[] arrayIci    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
                if (jpegIcIinfo != null)
                {
                    bmpp.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size && quality > 10)
                    {
                        quality -= 10;
                        CompressImage(sFile, dFile, quality, size, false);
                    }
                }
                else
                {
                    bmpp.Save(dFile, iSource.RawFormat);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// Create By Xu In 2018.09.29
        /// Edit By Xu In 2018.10.23 //Add BitMap.Dispose();
        /// Edit By Xu In 2018_10_29 //strFileName -> strFilePath ,Meaning You Need't Add ".FileFormat" In "strFilePath" But Must Assign ST_SaveOrLoadImgData.iImgFormat To Figure Out File Format;
        /// Function: Save Img To Native.
        /// </summary>
        /// <param name="strFileName">FilePath+FileName</param>
        /// <param name="stReadImgData">ST_SaveOrLoadImgData</param>
        /// <param name="iImgQuality">Low 0->100 High</param>
        /// <returns></returns>
        public string SaveImg(string strFilePath, ST_SaveOrLoadImgData stSaveImgData, int iImgQuality)
        {
            string strMsg      = string.Empty;
            string strFileName = string.Empty;

            try
            {
                if (strFilePath == null)
                {
                    return("FilePath_Is_Null");
                }

                switch (stSaveImgData.iImgFormat)//Edit By Xu In 2018_10_30
                {
                case 0:
                    if (
                        (strFilePath[strFilePath.Length - 4] == 46) &&    //"."
                        (strFilePath[strFilePath.Length - 3] == 98 || strFilePath[strFilePath.Length - 3] == 66) &&    //"bB"
                        (strFilePath[strFilePath.Length - 2] == 109 || strFilePath[strFilePath.Length - 2] == 77) &&    //"mM"
                        (strFilePath[strFilePath.Length - 1] == 112 || strFilePath[strFilePath.Length - 1] == 80)       //"pP"
                        )
                    {
                        strFileName = strFilePath;
                    }
                    else
                    {
                        strFileName = strFilePath + ".bmp";
                    }

                    break;

                case 1:
                    if (
                        (strFilePath[strFilePath.Length - 4] == 46) &&
                        (strFilePath[strFilePath.Length - 3] == 106 || strFilePath[strFilePath.Length - 3] == 74) &&    //"jJ"
                        (strFilePath[strFilePath.Length - 2] == 112 || strFilePath[strFilePath.Length - 2] == 80) &&    //"pP"
                        (strFilePath[strFilePath.Length - 1] == 103 || strFilePath[strFilePath.Length - 1] == 71)       //"gG"
                        )
                    {
                        strFileName = strFilePath;
                    }
                    else
                    {
                        strFileName = strFilePath + ".jpg";
                    }
                    break;

                case 2:
                    SaveImg(strFilePath, stSaveImgData);    //.imgdat
                    return("Format_Is_.imgdat");

                default:
                    return("File_Format_Params_Err");
                }

                if (stSaveImgData.iImgFormat == 0 && stSaveImgData.bUseOpcv == true)
                {
                    byte[]  byFileName  = System.Text.Encoding.Default.GetBytes(strFileName);
                    float[] AfarrParams = new float[3];
                    AfarrParams[0] = (float)strFileName.Length;
                    AfarrParams[1] = (float)stSaveImgData.iWidth;
                    AfarrParams[2] = (float)stSaveImgData.iHeight;

                    _cvFunc.SaveImgByOpcv(byFileName, stSaveImgData.byImgDataR, stSaveImgData.byImgDataG, stSaveImgData.byImgDataB, AfarrParams);
                    return(strMsg);
                }
                Bitmap bmp = new Bitmap(stSaveImgData.iWidth, stSaveImgData.iHeight, PixelFormat.Format24bppRgb);

                int iWidth  = stSaveImgData.iWidth;
                int iHeight = stSaveImgData.iHeight;
                int iLength = iWidth * iHeight;
                //获取图像的BitmapData对像
                System.Drawing.Imaging.BitmapData data = bmp.LockBits(new Rectangle(0, 0, iWidth, iHeight), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                //循环处理
                unsafe
                {
                    int   iOffset = data.Stride - data.Width * 3;
                    byte *ptr     = (byte *)(data.Scan0);
                    byte *ptr_b;
                    byte *ptr_g;
                    byte *ptr_r;
                    ptr_b = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataB, 0);
                    ptr_g = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataG, 0);
                    ptr_r = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataR, 0);
                    if (iOffset == 0)
                    {
                        for (int i = 0; i < iLength; i++)
                        {
                            *ptr++ = *ptr_b++;
                            *ptr++ = *ptr_g++;
                            *ptr++ = *ptr_r++;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < iHeight; i++)
                        {
                            for (int j = 0; j < iWidth; j++)
                            {
                                *ptr++ = *ptr_b++;
                                *ptr++ = *ptr_g++;
                                *ptr++ = *ptr_r++;
                            }
                            ptr += iOffset;
                        }
                    }
                }

                switch (stSaveImgData.iImgFormat)
                {
                case 0:
                    bmp.Save(strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case 1:
                    EncoderParameter  p;
                    EncoderParameters ps;

                    ps = new EncoderParameters(1);
                    if (iImgQuality > 100)
                    {
                        iImgQuality = 100;
                    }
                    else if (iImgQuality < 0)
                    {
                        iImgQuality = 80;
                    }
                    p           = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, iImgQuality);
                    ps.Param[0] = p;
                    bmp.Save(strFileName, GetCodecInfo("image/jpeg"), ps);
                    break;

                default:
                    bmp.Save(strFileName, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;
                }
                bmp.Dispose();//Edit By Xu In 2018.10.23
            }

            catch (Exception e)
            {
                strMsg += "SaveImgErr" + e.Message.ToString();
            }
            return(strMsg);
        }
Beispiel #10
0
        private static void WriteLongLat(string fileIn, string fileOut, byte latDeg, byte latMin, double latSec, byte lonDeg, byte lonMin, double lonSec, bool isWest, bool isNorth)
        {
            const int      length    = 25;
            Encoder        Enc       = Encoder.Transformation;
            var            EncParms  = new EncoderParameters(1);
            ImageCodecInfo CodecInfo = GetEncoderInfo("image/jpeg");

            // TODO: do not load the image to change again
            Image img = Image.FromFile(fileIn);

            PropertyItem[] PropertyItems = img.PropertyItems;
            int            oldArrLength  = PropertyItems.Length;
            var            newProperties = new PropertyItem[oldArrLength];

            img.PropertyItems.CopyTo(newProperties, 0);
            newProperties[0].Id    = 0x0002;
            newProperties[0].Type  = 5; //5-R 4-L 3-S
            newProperties[0].Len   = length;
            newProperties[0].Value = new byte[length];
            try {
                for (int i = 0; i < length; i++)
                {
                    newProperties[0].Value[i] = 0;
                }
            }
            catch (Exception ex) {
                logger.InfoException("in WriteLongLat got an exception", ex);
            }
            //PropertyItems[0].Value = Pic.GetPropertyItem(4).Value; // bDescription;
            newProperties[0].Value[0] = latDeg;
            newProperties[0].Value[8] = latMin;
            byte secHelper  = (byte)(latSec / 2.56);
            byte secRemains = (byte)((latSec - (secHelper * 2.56)) * 100);

            newProperties[0].Value[16] = secRemains; // add to the sum below x_x_*17_+16
            newProperties[0].Value[17] = secHelper;  // multiply by 2.56
            newProperties[0].Value[20] = 100;
            img.SetPropertyItem(newProperties[0]);
            newProperties[1].Id    = 0x0004;
            newProperties[1].Type  = 5; //5-R 4-L 3-S
            newProperties[1].Len   = length;
            newProperties[1].Value = new byte[length];
            try {
                for (int i = 0; i < length; i++)
                {
                    newProperties[1].Value[i] = 0;
                }
            }
            catch (Exception e) {
                Console.WriteLine("Error {0}", e);
            }
            newProperties[1].Value[0] = lonDeg;
            newProperties[1].Value[8] = lonMin;
            secHelper  = (byte)(lonSec / 2.56);
            secRemains = (byte)((lonSec - (secHelper * 2.56)) * 100);
            newProperties[1].Value[16] = secRemains;
            // add to the sum bellow x_x_*17_+16
            newProperties[1].Value[17] = secHelper;
            // multiply by 2.56
            newProperties[1].Value[20] = 100;
            // multiply by 2.56

            //PropertyItem current = Pic.GetPropertyItem(2);
            img.SetPropertyItem(newProperties[1]);
            //GPS Version
            newProperties[0].Id       = 0x0000;
            newProperties[0].Type     = 1;
            newProperties[0].Len      = 4;
            newProperties[0].Value[0] = 2;
            newProperties[0].Value[1] = 2;
            newProperties[0].Value[2] = 0;
            newProperties[0].Value[3] = 0;
            img.SetPropertyItem(newProperties[0]);

            //GPS Lat REF
            newProperties[0].Id   = 0x0001;
            newProperties[0].Type = 2;
            newProperties[0].Len  = 2;
            if (isNorth)
            {
                newProperties[0].Value[0] = 78; //ASCII for N
            }
            else
            {
                newProperties[0].Value[0] = 83; //ASCII for S
            }

            newProperties[0].Value[1] = 0;
            img.SetPropertyItem(newProperties[0]);


            //GPS Lon REF
            newProperties[0].Id   = 0x0003;
            newProperties[0].Type = 2; //5-R 4-L 3-S
            newProperties[0].Len  = 2;
            if (isWest == false)
            {
                newProperties[0].Value[0] = 69; //ASCII for E
            }
            else
            {
                newProperties[0].Value[0] = 87; //ASCII for W
            }
            newProperties[0].Value[1] = 0;
            img.SetPropertyItem(newProperties[0]);

            // we cannot store in the same image, so use a temporary image instead
            string FilenameTemp = fileIn + ".temp";
            // for lossless rewriting must rotate the image by 90 degrees!
            EncoderParameter EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate90);

            EncParms.Param[0] = EncParm;
            // now write the rotated image with new description
            img.Save(FilenameTemp, CodecInfo, EncParms);
            // for computers with low memory and large pictures: release memory now
            img.Dispose();
            img = null;
            GC.Collect();
            // delete the original file, will be replaced later
            if (string.IsNullOrEmpty(fileOut))
            {
                File.Delete(fileIn);
            }
            // now must rotate back the written picture
            img               = Image.FromFile(FilenameTemp);
            EncParm           = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate270);
            EncParms.Param[0] = EncParm;
            if (string.IsNullOrEmpty(fileOut))
            {
                img.Save(fileIn, CodecInfo, EncParms);
            }
            else
            {
                img.Save(fileOut, CodecInfo, EncParms);
            }
            // release memory now
            img.Dispose();
            img = null;
            GC.Collect();
            // delete the temporary picture
            File.Delete(FilenameTemp);
        }
Beispiel #11
0
        public static string SaveMarkerPhoto(byte[] markerPhoto, bool mini)
        {
            var virtualPath = $@"{MarkerPhotos}\{Guid.NewGuid()}.jpg";
            var jpgEncoder  = GetEncoder(ImageFormat.Jpeg);
            var siteRoot    = GetPublicContent();

            if (siteRoot != null)
            {
                var savePath = $@"{siteRoot}\{virtualPath}";
                using (var stream = new MemoryStream(markerPhoto))
                {
                    var myEncoder =
                        Encoder.Quality;
                    var myEncoderParameters = new EncoderParameters(1);
                    var myEncoderParameter  = new EncoderParameter(myEncoder, 50L);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    var firstBitmap = new Bitmap(stream);

                    if (Array.IndexOf(firstBitmap.PropertyIdList, 274) > -1)
                    {
                        var orientation = (int)firstBitmap.GetPropertyItem(274).Value[0];
                        switch (orientation)
                        {
                        case 1:
                            // No rotation required.
                            break;

                        case 2:
                            firstBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
                            break;

                        case 3:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            break;

                        case 4:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                            break;

                        case 5:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate90FlipX);
                            break;

                        case 6:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            break;

                        case 7:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate270FlipX);
                            break;

                        case 8:
                            firstBitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            break;
                        }
                        // This EXIF data is now invalid and should be removed.
                        firstBitmap.RemovePropertyItem(274);
                    }

                    if (!mini)
                    {
                        firstBitmap.Save(savePath);
                    }
                    else
                    {
                        firstBitmap.Save(savePath, jpgEncoder, myEncoderParameters);
                    }
                }
            }
            else
            {
                throw new MyException(Errors.UnknownError);
            }
            return(virtualPath);
        }
Beispiel #12
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Beispiel #13
0
        /// <summary>
        /// GetImageBytesWithJpegQuality
        /// </summary>
        /// <param name="image"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public static byte[] GetImageBytesWithJpegQuality(Image image, int level)
        {
            if (image == null)
            {
                return(null);
            }
            byte[] buff = null;

            try
            {
                if (myEncoderParameters == null)
                {
                    myImageCodecInfo = null;
                    ImageCodecInfo[] en_list = ImageCodecInfo.GetImageEncoders();
                    foreach (ImageCodecInfo en in en_list)
                    {
                        if (en.MimeType.ToLower() == "image/jpeg")
                        {
                            myImageCodecInfo = en;
                            break;
                        }
                    }

                    System.Drawing.Imaging.Encoder mQuality = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameter myEncoderParameter     = new EncoderParameter(mQuality, (long)level);//25L);

                    myEncoderParameters          = new EncoderParameters(1);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                }

                MemoryStream mem_stream = new MemoryStream();
                image.Save(mem_stream, myImageCodecInfo, myEncoderParameters);
                buff = mem_stream.ToArray();
                mem_stream.Close();

                return(buff);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }

            try
            {
                MemoryStream mem_stream = new MemoryStream();
                image.Save(mem_stream, ImageFormat.Jpeg);
                buff = mem_stream.ToArray();
                mem_stream.Close();

                return(buff);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
            try
            {
                MemoryStream mem_stream = new MemoryStream();
                image.Save(mem_stream, ImageFormat.Gif);
                buff = mem_stream.ToArray();
                mem_stream.Close();

                return(buff);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
            try
            {
                MemoryStream mem_stream = new MemoryStream();
                image.Save(mem_stream, ImageFormat.Bmp);
                buff = mem_stream.ToArray();
                mem_stream.Close();

                return(buff);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
            return(null);
        }
Beispiel #14
0
    /// <summary>
    /// 添加图片水印
    /// </summary>
    /// <param name="oldFilePath">原始图片路径</param>
    /// <param name="newFilePath">将要添加水印图片路径</param>
    /// <param name="waterPosition">水印位置</param>
    /// <param name="waterImagePath">水印图片路径</param>
    /// <param name="transparency">透明度</param>
    /// <param name="quality">质量</param>
    public static void CreateWaterImage(string oldFilePath, string newFilePath, int waterPosition, string waterImagePath, int watermarkTransparency, int quality)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(oldFilePath);

        Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);

        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);

        g.DrawImage(image, 0, 0, image.Width, image.Height);

        //设置透明度
        System.Drawing.Image watermark = new Bitmap(waterImagePath);
        ImageAttributes imageAttributes = new ImageAttributes();
        ColorMap colorMap = new ColorMap();
        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
        ColorMap[] remapTable = { colorMap };
        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        float transparency = 0.5F;
        if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
        {
            transparency = (watermarkTransparency / 10.0F);
        }

        float[][] colorMatrixElements = {
                                                    new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f}, //注意:倒数第二处为0.0f为完全透明,1.0f为完全不透明
                                                    new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                                };
        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        int _width = image.Width;
        int _height = image.Height;
        int xpos = 0;
        int ypos = 0;
        int WatermarkWidth = 0;
        int WatermarkHeight = 0;
        double bl = 1d;
        //计算水印图片的比率
        //取背景的1/4宽度来比较
        if ((_width > watermark.Width * 2) && (_height > watermark.Height * 2))
        {
            bl = 1;
        }
        else if ((_width > watermark.Width * 2) && (_height < watermark.Height * 2))
        {
            bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);

        }
        else if ((_width < watermark.Width * 2) && (_height > watermark.Height * 2))
        {
            bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
        }
        else
        {
            if ((_width * watermark.Height) > (_height * watermark.Width))
            {
                bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);
            }
            else
            {
                bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
            }
        }
        WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
        WatermarkHeight = Convert.ToInt32(watermark.Height * bl);
        switch (waterPosition)
        {
            case 3:
                xpos = _width - WatermarkWidth - 10;
                ypos = 10;
                break;
            case 2:
                xpos = 10;
                ypos = _height - WatermarkHeight - 10;
                break;
            case 5:
                xpos = _width / 2 - WatermarkWidth / 2;
                ypos = _height / 2 - WatermarkHeight / 2;
                break;
            case 1:
                xpos = 10;
                ypos = 10;
                break;
            case 4:
            default:
                xpos = _width - WatermarkWidth - 10;
                ypos = _height - WatermarkHeight - 10;
                break;
        }
        g.DrawImage(watermark, new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
        try
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];

            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                bmp.Save(newFilePath, ici, encoderParams);
            }
            else
            {
                bmp.Save(newFilePath);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            watermark.Dispose();
            imageAttributes.Dispose();
            image.Dispose();
            bmp.Dispose();
        }
    }
Beispiel #15
0
        public void SaveMultipage(Image[] bmp, string location, string type)
        {
            if (bmp != null)
            {
                try
                {
                    ImageCodecInfo codecInfo = getCodecForstring(type);

                    for (int i = 0; i < bmp.Length; i++)
                    {
                        if (bmp[i] == null)
                        {
                            break;
                        }
                        bmp[i] = (Image)ConvertToBitonal((Bitmap)bmp[i]);
                    }

                    if (bmp.Length == 1)
                    {
                        EncoderParameters iparams    = new EncoderParameters(1);
                        Encoder           iparam     = Encoder.Compression;
                        EncoderParameter  iparamPara = new EncoderParameter(iparam, (long)(EncoderValue.CompressionCCITT4));
                        iparams.Param[0] = iparamPara;
                        bmp[0].Save(location, codecInfo, iparams);
                    }
                    else if (bmp.Length > 1)
                    {
                        Encoder           saveEncoder;
                        Encoder           compressionEncoder;
                        EncoderParameter  SaveEncodeParam;
                        EncoderParameter  CompressionEncodeParam;
                        EncoderParameters EncoderParams = new EncoderParameters(2);

                        saveEncoder        = Encoder.SaveFlag;
                        compressionEncoder = Encoder.Compression;

                        // Save the first page (frame).
                        SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame);
                        CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                        EncoderParams.Param[0] = CompressionEncodeParam;
                        EncoderParams.Param[1] = SaveEncodeParam;

                        File.Delete(location);
                        bmp[0].Save(location, codecInfo, EncoderParams);


                        for (int i = 1; i < bmp.Length; i++)
                        {
                            if (bmp[i] == null)
                            {
                                break;
                            }

                            SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage);
                            CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                            EncoderParams.Param[0] = CompressionEncodeParam;
                            EncoderParams.Param[1] = SaveEncodeParam;
                            bmp[0].SaveAdd(bmp[i], EncoderParams);
                        }

                        SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush);
                        EncoderParams.Param[0] = SaveEncodeParam;
                        bmp[0].SaveAdd(EncoderParams);
                    }
                    //return true;
                }
                catch (System.Exception ee)
                {
                    throw new Exception(ee.Message + "  Error in saving as multipage ");
                }
            }
            //return false;
        }
    public static void AddThumbnail(string imagePath, int width, string fileNameAddition, string fileSavePath)
    {
        bool renameImage = true;
        string savePath = "";
        try
        {
        System.IO.Stream imageStream = File.Open(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        try
        {
        string imageNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(imagePath);

        savePath = fileSavePath.TrimEnd('\\') + "\\" + imageNameWithoutExt;
        savePath += fileNameAddition;
        savePath += ".jpg";

        if (!File.Exists(savePath))
        {

            System.Drawing.Image mg = System.Drawing.Image.FromStream(imageStream, true);

            double multiplier = (double)width / mg.Width;
            int newWidth = width;
            int newHeight = (int)(mg.Height * multiplier);

           Size newSize = new Size(newWidth, newHeight);

            Bitmap bp = new Bitmap(newSize.Width, newSize.Height);

            Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            Rectangle rect = new Rectangle(0, 0, newSize.Width, newSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            foreach (PropertyItem pItem in mg.PropertyItems)
            {
                bp.SetPropertyItem(pItem);
            }

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo codec = null;
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType.Equals("image/jpeg"))
                    codec = codecs[i];
            }

            if (codec != null)
            {
                EncoderParameters encoderParameters = new EncoderParameters(2);

                System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameter encoderParameter = new EncoderParameter(encoder, 95L);
                encoderParameters.Param[0] = encoderParameter;

                encoder = System.Drawing.Imaging.Encoder.ColorDepth;
                encoderParameter = new EncoderParameter(encoder, 100L);
                encoderParameters.Param[1] = encoderParameter;

                bp.Save(savePath, codec, encoderParameters);

            }

        }
        }
        catch
        {
            renameImage = false;
        }
        finally
        {
            imageStream.Close();
        }
        }
        catch
        {
            //Could not open image
        }

        //if (insituResize && renameImage && savePath != "")
        //{
        //    System.IO.File.Delete(imagePath);
        //    System.IO.File.Move(savePath, imagePath);
        //}
    }
Beispiel #17
0
    /// <summary>
    /// 图片水印
    /// </summary>
    /// <param name="imgPath">服务器图片相对路径</param>
    /// <param name="filename">保存文件名</param>
    /// <param name="watermarkFilename">水印文件相对路径</param>
    /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
    /// <param name="quality">附加水印图片质量,0-100</param>
    /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
    public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
    {
        byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
            filename = HttpContext.Current.Server.MapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
                watermarkFilename = "/" + watermarkFilename;
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
                return;
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                return;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;
            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                transparency = (watermarkTransparency / 10.0F);

            float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 2:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 3:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 4:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 5:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 6:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 7:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 8:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 9:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
    }
Beispiel #18
0
        private void ProcessImage(IFile w, IProgress <ModelProgressUpdate> progress = null)
        {
            if (Cancel)
            {
                Interlocked.Decrement(ref _totalImages);
                progress?.Report(new ModelProgressUpdate(_totalImages, _doneImages));
                return;
            }

            if (w != null)
            {
                var outFmt = w.Options.OutputOptions.OutputFormat == Format.Default ? Options.OutputOptions.OutputFormat : w.Options.OutputOptions.OutputFormat;

                // Load Image
                Image b = null;
                try
                {
                    b = StaticImageUtils.LoadImage(w);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                }

                if (b == null)
                {
                    Interlocked.Decrement(ref _totalImages);
                    progress?.Report(new ModelProgressUpdate(_totalImages, _doneImages));
                    return;
                }

                #region Process Steps

                var clone = new Bitmap(b.Width, b.Height, PixelFormat.Format32bppPArgb);
                using (var gr = Graphics.FromImage(clone))
                {
                    gr.DrawImage(b, new Rectangle(0, 0, clone.Width, clone.Height));
                }
                b.Dispose();
                b = clone;

                if (w.Options.Rotation != Rotation.Default || Options.EnableRotation)
                {
                    b.RotateImage(w.Options.EnableRotation ? w.Options.Rotation : Options.Rotation);
                }

                if (Options.EnableResize || w.Options.EnableResize)
                {
                    b = b.ResizeImage(w.Options.EnableResize ? w.Options.ResizeOptions : Options.ResizeOptions);
                }

                if (Options.EnableCrop || w.Options.EnableCrop)
                {
                    b = b.CropImage(w.Options.EnableCrop ? w.Options.CropOptions : Options.CropOptions);
                }

                if (Options.EnableWatermark || w.Options.EnableWatermark)
                {
                    b.WatermarkImage(w.Options.EnableWatermark ? w.Options.WatermarkOptions : Options.WatermarkOptions);
                }

                b = b.AdjustImage(w.Options.EnableAdjustments ? w.Options.AdjustmentOptions : Options.AdjustmentOptions);

                #endregion

                // Filename
                var name = GenerateFilename(w, b);

                // Output Path
                var outpath = GenerateOutputPath(w, name, outFmt);

                #region Select Encoder

                var encoder = ImageFormat.Jpeg;
                // Save
                switch (outFmt)
                {
                case Format.Png:
                    encoder = ImageFormat.Png;
                    break;

                case Format.Gif:
                    encoder = ImageFormat.Gif;
                    break;

                case Format.Tiff:
                    encoder = ImageFormat.Tiff;
                    break;

                case Format.Bmp:
                    encoder = ImageFormat.Bmp;
                    break;
                }

                #endregion

                if (outFmt == Format.Jpg)
                {
                    var myEncoderParameters = new EncoderParameters(1);
                    var myencoder           = Encoder.Quality;
                    var myEncoderParameter  = new EncoderParameter(myencoder, (long)(Options.OutputOptions.JpegQuality * 100));
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    b.Save(outpath, StaticImageUtils.GetEncoder(encoder), myEncoderParameters);
                }
                else
                {
                    b.Save(outpath, encoder);
                }
                b.Dispose();
                outpath.Close();
            }

            Interlocked.Increment(ref _doneImages);
            progress?.Report(new ModelProgressUpdate(_totalImages, _doneImages));
        }
Beispiel #19
0
    /// <summary>
    /// 文字水印
    /// </summary>
    /// <param name="imgPath">服务器图片相对路径</param>
    /// <param name="filename">保存文件名</param>
    /// <param name="watermarkText">水印文字</param>
    /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
    /// <param name="quality">附加水印图片质量,0-100</param>
    /// <param name="fontname">字体</param>
    /// <param name="fontsize">字体大小</param>
    public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
    {
        byte[] _ImageBytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imgPath));
            Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
            filename = HttpContext.Current.Server.MapPath(filename);

            Graphics g = Graphics.FromImage(img);
            Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF crSize;
            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (float)img.Width * (float).01;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 2:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = (float)img.Height * (float).01;
                    break;
                case 3:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 4:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 5:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 6:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 7:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 8:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 9:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
    }
Beispiel #20
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="src">原图片文件流</param>
        /// <param name="dest">压缩后图片文件流</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(Stream src, Stream dest, int flag = 90, int size = 1024, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            if (sfsc && src.Length < size * 1024)
            {
                src.CopyTo(dest);
                return(true);
            }

            using (Image iSource = Image.FromStream(src))
            {
                ImageFormat tFormat = iSource.RawFormat;
                int         dHeight = iSource.Height;
                int         dWidth = iSource.Width;
                int         sW, sH;
                //按比例缩放
                Size temSize = new Size(iSource.Width, iSource.Height);
                if (temSize.Width > dHeight || temSize.Width > dWidth)
                {
                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                    {
                        sW = dWidth;
                        sH = (dWidth * temSize.Height) / temSize.Width;
                    }
                    else
                    {
                        sH = dHeight;
                        sW = (temSize.Width * dHeight) / temSize.Height;
                    }
                }
                else
                {
                    sW = temSize.Width;
                    sH = temSize.Height;
                }

                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.WhiteSmoke);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
                    }

                    //以下代码为保存图片时,设置压缩质量
                    using (EncoderParameters ep = new EncoderParameters())
                    {
                        long[] qy = new long[1];
                        qy[0] = flag;//设置压缩的比例1-100
                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
                        {
                            ep.Param[0] = eParam;
                            try
                            {
                                ImageCodecInfo[] arrayIci    = ImageCodecInfo.GetImageEncoders();
                                ImageCodecInfo   jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
                                if (jpegIcIinfo != null)
                                {
                                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
                                    if (dest.Length > 1024 * size)
                                    {
                                        flag = flag - 10;
                                        CompressImage(src, dest, flag, size, false);
                                    }
                                }
                                else
                                {
                                    bmp.Save(dest, tFormat);
                                }
                                return(true);
                            }
                            catch
                            {
                                return(false);
                            }
                        }
                    }
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Overwrites the specified file on disk with a new version of the file rotated according
        /// to the specified Orientation.  Exceptions generated by an error writing the new file will
        /// bubble up from this method.
        ///
        /// Before the original file is overwritten, a copy is made in the temp files folder (so that
        /// the original image isn't lost if the write of the rotated version fails).  This temporary
        /// copy is deleted before the method returns if the write of the new rotated image is successful.
        /// </summary>
        /// <param name="filename">The fully-specified name of the file to rotate. </param>
        /// <param name="orientation">The orientation to apply to the rotated file. </param>
        public static void RotateAndSaveImageFile(string filename, Orientation orientation)
        {
            if (orientation == Orientation.Initial)
            {
                //No rotation was specified, so no need to change anything.
                return;
            }

            //Make a backup copy of the original image in the temp folder (so that if we hit a
            //failure during writing of the new image, both the original and new copies of the
            //image aren't gone).
            string backupFilename = GetBackupFilename(filename);

            System.IO.File.Copy(filename, backupFilename, true);

            //Since our original image is dependant on the existing file on disk to be saved,
            //we can't delete the original image file until the rotated image file is written.
            //Get a temporary file that we'll use below to write the new image data.
            string tempFilename = System.IO.Path.GetTempFileName();

            //Load the image from the specified filename
            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (Image image = Image.FromStream(fileStream, true, false))
                {
                    //Calculate the new value for the EXIF rotation property, and set it on the image.  (This is
                    //calculated as the original EXIF rotation as read from the file, with the rotation performed
                    //in the app applied to that value.  Thus if the original EXIF rotation tag was incorrect,
                    //and the user manually rotated the image to be upright, the tag will continue to be incorrect.)
                    PropertyItem rotationPropertyItem         = image.GetPropertyItem(ROTATION_PROPERTY_ID);
                    Orientation  originalOrientation          = OrientationFromExifRotationPropertyValue(rotationPropertyItem.Value[0]);
                    Orientation  newOrientation               = (Orientation)((((int)originalOrientation) + ((int)orientation)) % 4);
                    int          newExifRotationPropertyValue = ExifRotationPropertyValueFromOrientation(newOrientation);
                    rotationPropertyItem.Value[0] = (byte)newExifRotationPropertyValue;
                    image.SetPropertyItem(rotationPropertyItem);

                    //Setup the EncoderParameters with the information that we will be performing when
                    //saving the rotated file.
                    EncoderParameters encoderParams        = new EncoderParameters(1);
                    EncoderValue      rotationEncoderValue = EncoderValueFromOrientation(orientation);
                    EncoderParameter  rotationParam        = new EncoderParameter(Encoder.Transformation, (long)rotationEncoderValue);
                    encoderParams.Param[0] = rotationParam;

                    //Setup the .jpg ImageCodecInfo that we need to save the rotated file.
                    ImageCodecInfo jpegCodecInfo = GetEncoderInfo("image/jpeg");

                    using (FileStream outFileStream = new FileStream(tempFilename, FileMode.Open, FileAccess.Write))
                    {
                        image.Save(outFileStream, jpegCodecInfo, encoderParams);
                    }
                }
            }

            //Delete the original image (making room for us to rename the new, rotated copy).
            System.IO.File.Delete(filename);

            try
            {
                //Now, move the rotated image that we saved out as a temporary file to the name and
                //location of the original file.
                File.Move(tempFilename, filename);
            }
            catch
            {
                //An error occurred moving the rotated file.  Try and retore the original file from
                //the copy that we saved in the temp folder, so that the file isn't just "gone" as
                //far as the user can tell.
                File.Move(backupFilename, filename);

                //Let the exception bubble up -- an error dialog will be displayed to the user.
                throw;
            }

            //Since we got to this point without an exception being thrown, the write of the new
            //file was apparently successful.  Delete the copy of the original file that we made
            //in the temp folder.
            System.IO.File.Delete(backupFilename);
        }
Beispiel #22
0
    static void rebdqulity_pic(string szdir, long lqulity)
    {
        int i = 0;
        Bitmap myBitmap;
        ImageCodecInfo myImageCodecInfo;
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;

        // Get an ImageCodecInfo object that represents the JPEG codec.
        myImageCodecInfo = GetEncoderInfo("image/jpeg");
        myEncoder = Encoder.Quality;
        myEncoderParameters = new EncoderParameters(1);

        myEncoderParameter = new EncoderParameter(myEncoder, lqulity);
        myEncoderParameters.Param[0] = myEncoderParameter;
        string szsavedir = Directory.CreateDirectory(szdir + "\\icon").FullName.ToString();
        string[] szfiles = Directory.GetFiles(szdir, "*.jpg");
        foreach (string szfile in szfiles)
        {
            myBitmap = new Bitmap(szfile);
            myBitmap.Save(szsavedir + @"\quli" + i.ToString() + ".jpg", myImageCodecInfo, myEncoderParameters);

            i++;

        }
    }
Beispiel #23
0
        public static void Compressimage(Stream sourcePath, string targetPath, String filename)
        {
            try
            {
                using (var image = Image.FromStream(sourcePath))
                {
                    float  maxHeight = 900.0f;
                    float  maxWidth  = 900.0f;
                    int    newWidth;
                    int    newHeight;
                    string extension;
                    Bitmap originalBMP    = new Bitmap(sourcePath);
                    int    originalWidth  = originalBMP.Width;
                    int    originalHeight = originalBMP.Height;

                    if (originalWidth > maxWidth || originalHeight > maxHeight)
                    {
                        // To preserve the aspect ratio
                        float ratioX = (float)maxWidth / (float)originalWidth;
                        float ratioY = (float)maxHeight / (float)originalHeight;
                        float ratio  = Math.Min(ratioX, ratioY);
                        newWidth  = (int)(originalWidth * ratio);
                        newHeight = (int)(originalHeight * ratio);
                    }
                    else
                    {
                        newWidth  = (int)originalWidth;
                        newHeight = (int)originalHeight;
                    }
                    Bitmap   bitMAP1  = new Bitmap(originalBMP, newWidth, newHeight);
                    Graphics imgGraph = Graphics.FromImage(bitMAP1);
                    extension = Path.GetExtension(targetPath);
                    if (extension == ".png" || extension == ".gif")
                    {
                        imgGraph.SmoothingMode     = SmoothingMode.AntiAlias;
                        imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);


                        bitMAP1.Save(targetPath, image.RawFormat);

                        bitMAP1.Dispose();
                        imgGraph.Dispose();
                        originalBMP.Dispose();
                    }
                    else if (extension == ".jpg")
                    {
                        imgGraph.SmoothingMode     = SmoothingMode.AntiAlias;
                        imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                        ImageCodecInfo    jpgEncoder          = GetEncoder(ImageFormat.Jpeg);
                        Encoder           myEncoder           = Encoder.Quality;
                        EncoderParameters myEncoderParameters = new EncoderParameters(1);
                        EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, 50L);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        bitMAP1.Save(targetPath, jpgEncoder, myEncoderParameters);

                        bitMAP1.Dispose();
                        imgGraph.Dispose();
                        originalBMP.Dispose();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #24
0
        private void saveImageExistingMultiplePage(Image[] bmp, Image origionalFile, string type, int PageNumber, string location)
        {
            try
            {
                //Now load the Codecs
                ImageCodecInfo codecInfo = getCodecForstring(type);

                Encoder           saveEncoder;
                Encoder           compressionEncoder;
                EncoderParameter  SaveEncodeParam;
                EncoderParameter  CompressionEncodeParam;
                EncoderParameters EncoderParams = new EncoderParameters(2);
                Bitmap            pages;
                Bitmap            NextPage;


                saveEncoder        = Encoder.SaveFlag;
                compressionEncoder = Encoder.Compression;

                origionalFile.SelectActiveFrame(FrameDimension.Page, 0);
                pages = new Bitmap(origionalFile);
                pages = ConvertToBitonal(pages);

                // Save the first page (frame).
                SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame);
                CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                EncoderParams.Param[0] = CompressionEncodeParam;
                EncoderParams.Param[1] = SaveEncodeParam;

                pages.Save(location, codecInfo, EncoderParams);


                for (int i = 1; i < PageNumber; i++)
                {
                    SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage);
                    CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                    EncoderParams.Param[0] = CompressionEncodeParam;
                    EncoderParams.Param[1] = SaveEncodeParam;

                    origionalFile.SelectActiveFrame(FrameDimension.Page, i);
                    NextPage = new Bitmap(origionalFile);
                    NextPage = ConvertToBitonal(NextPage);
                    pages.SaveAdd(NextPage, EncoderParams);
                }

                for (int i = 0; i < bmp.Length; i++)
                {
                    SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage);
                    CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                    EncoderParams.Param[0] = CompressionEncodeParam;
                    EncoderParams.Param[1] = SaveEncodeParam;
                    bmp[i] = (Bitmap)ConvertToBitonal((Bitmap)bmp[i]);
                    pages.SaveAdd(bmp[i], EncoderParams);
                }

                SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush);
                EncoderParams.Param[0] = SaveEncodeParam;
                pages.SaveAdd(EncoderParams);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            double proporcao;
            int    w, h, xCrop, yCrop;
            string imgName           = Request.QueryString["img"];
            byte   crop              = Convert.ToByte(Request.QueryString["c"]);
            string colorName         = Request.QueryString["b"];
            int    interpolationMode = Convert.ToInt16(Request.QueryString["i"]);

            //Precisão do redimensionamento
            int p = Convert.ToInt32(Request.QueryString["p"]);

            int widthT  = Convert.ToInt32(Request.QueryString["w"]);
            int heightT = Convert.ToInt32(Request.QueryString["h"]);

            //Nome da imagem a ser cacheada ou comparada
            string strImg = imgName.Substring(0, imgName.LastIndexOf('.')) + "_" + widthT + "x" + heightT + "_" + crop.ToString() + (string.IsNullOrEmpty(colorName) ? "" : "_" + colorName) + "_" + interpolationMode + "_" + p + imgName.Substring(imgName.LastIndexOf('.'));

            //Path com as imagens "cacheadas"
            string cachePath = Path.Combine(Server.MapPath("~/Arquivos/ThumbCache/"), strImg);

            //Dados da última
            DateTime dataModCache = File.GetLastWriteTime(Server.MapPath(imgName));
            DateTime dataModImg   = File.GetLastWriteTime(cachePath);

            int comparacao = DateTime.Compare(dataModCache, dataModImg);

            //Se o arquivo já existe no cache
            if (File.Exists(cachePath) && comparacao <= 0)
            {
                OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(cachePath));
                HttpContext.Current.Response.WriteFile(cachePath);
                return;
            }
            else
            {
                //Cria diretório com as imagens (parâmetro)
                Directory.CreateDirectory(Path.GetDirectoryName(cachePath));

                //Deleta se já existe imagem cacheada
                if (File.Exists(cachePath))
                {
                    File.Delete(cachePath);
                }

                //Cria o "bitmap" com imagem original
                string      imgPath = HttpContext.Current.Request.MapPath("~/" + imgName);
                Bitmap      bmp     = new Bitmap(imgPath);
                ImageFormat formato = bmp.RawFormat;
                double      widthO  = bmp.Size.Width;
                double      heightO = bmp.Size.Height;

                //Caso só largura ou altura sejam transmitidas
                if (widthT == 0 || heightT == 0)
                {
                    //Cálculo com base na largura (widthT)
                    if (widthT > 0)
                    {
                        heightO = widthT / (widthO / heightO);
                        widthO  = widthT;
                        heightT = Convert.ToInt32(heightO);
                        //Cálculo com base na altura (heightT)
                    }
                    else
                    {
                        widthO  = heightT / (heightO / widthO);
                        heightO = heightT;
                        widthT  = Convert.ToInt32(widthO);
                    }
                }
                else
                {
                    //Caso opção seja "CROPAR"
                    if (crop == 1)
                    {
                        //Se uma das medidas originais forem MAIORES que o "Target"
                        if (widthO > widthT || heightO > heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO > widthT || heightO > heightT)
                            {
                                widthO--;
                                heightO = widthO / proporcao;
                                if (widthO <= widthT && heightO <= heightT)
                                {
                                    break;
                                }
                            }
                        }
                        //Se uma das medidas originais forem MENORES que o "Target"
                        if (widthO < widthT || heightO < heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO < widthT || heightO < heightT)
                            {
                                widthO++;
                                heightO = widthO / proporcao;
                                if (widthO >= widthT && heightO >= heightT)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        //Se uma das medidas originais forem MAIORES que o "Target"
                        if (widthO > widthT || heightO > heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO > widthT || heightO > heightT)
                            {
                                widthO--;
                                heightO = widthO / proporcao;
                                if (widthO <= widthT && heightO <= heightT)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            //Se uma das medidas originais forem MENORES que o "Target"
                            if (widthO < widthT || heightO < heightT)
                            {
                                proporcao = widthO / heightO;
                                while (widthO < widthT && heightO < heightT)
                                {
                                    widthO++;
                                    heightO = widthO / proporcao;
                                    if (widthO >= widthT && heightO >= heightT)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                //Medidas finais (incluindo valor de precisão)
                w = Convert.ToInt32(widthO) + p;
                h = Convert.ToInt32(heightO) + p;

                //Calcula as coordenadas para corte
                xCrop = Convert.ToInt32((w - widthT) / 2);
                yCrop = Convert.ToInt32((h - heightT) / 2);

                Bitmap bmpT = new Bitmap(widthT, heightT);

                EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 95L);
                //Image codec
                ImageCodecInfo    imgCodec      = ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.FormatID == formato.Guid);
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                //Cor de fundo
                Color bg = Color.White;

                //Caso a cor não seja transmitida
                if (string.IsNullOrEmpty(colorName))
                {
                    //se PNG "transparent"
                    if (formato.Equals(ImageFormat.Png) || formato.Equals(ImageFormat.Gif))
                    {
                        bg = Color.Transparent;
                    }
                }
                else
                {
                    try
                    {
                        //Html color (hex)
                        bg = ColorTranslator.FromHtml("#" + colorName);
                    }
                    catch (Exception)
                    {
                        //Html color
                        bg = ColorTranslator.FromHtml(colorName);
                    }
                }

                //Manipula e salva em cache
                using (Graphics g = Graphics.FromImage(bmpT))
                {
                    g.CompositingQuality = CompositingQuality.HighSpeed;
                    g.InterpolationMode  = interpolationMode == 0 ? InterpolationMode.HighQualityBicubic : InterpolationMode.HighQualityBilinear;
                    g.CompositingMode    = CompositingMode.SourceCopy;
                    g.Clear(bg);
                    g.DrawImage(bmp, -xCrop, -yCrop, w, h);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        bmpT.Save(memoryStream, imgCodec, encoderParams);
                        OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(imgPath));
                        using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
                        {
                            memoryStream.WriteTo(diskCacheStream);
                        }
                        memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    }
                }

                bmp.Dispose();
                bmpT.Dispose();
            }
        }
        catch (Exception ex)
        {
            Font     font = new Font("verdana", 12);
            Bitmap   bmp  = new Bitmap(ex.Message.Length * 10, 50);
            Graphics g    = Graphics.FromImage(bmp);
            g.DrawString(ex.Message.Replace("'", ""), font, new SolidBrush(Color.White), new PointF(5.0F, 5.0F));
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
        }
    }
Beispiel #26
0
 public MyEncoder()
 {
     System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
     EncoderParameter myEncoderParameter = new EncoderParameter(encoder, 15L);
     myEncoderParameters.Param[0] = myEncoderParameter;
 }
Beispiel #27
0
    /// <summary>
    /// 加图片水印
    /// </summary>
    /// <param name="imgPath">原图文件名物理路径</param>
    /// <param name="filename">生成文件名物理路径</param>
    /// <param name="watermarkFilename">水印文件名物理路径</param>
    /// <param name="positon">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
    /// <param name="quality">附加图片质量,0--100之间,值大质量高</param>
    /// <param name="watermarkTransparency">水印的透明度 1--100 100为不透明</param>

    public static bool AddImageSignPic(string imgPath, string filename, string watermarkFilename, Enums.Position positon, int quality, int watermarkTransparency, int minWidth, int minHeight)
    {
        using (Bitmap img = new Bitmap(imgPath))
        {
            Graphics g ;
                //如果原图片是索引像素格式之列的,则需要转换
                if (IsPixelFormatIndexed(img.PixelFormat))
                {
                    using (Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb))
                    {
                        g = Graphics.FromImage(bmp);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(img, 0, 0);
                    }

                }
                else
                {
                    g = Graphics.FromImage(img);
                    //设置高质量插值法
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                }
                int watermarkStatus = (int)positon;


                using (System.Drawing.Image watermark = new Bitmap(watermarkFilename))
                {

                    if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                    {
                        return false;
                    }
                    if (img.Width < minWidth || img.Height < minHeight)
                    {
                        return false;
                    }


                    using (ImageAttributes imageAttributes = new ImageAttributes())
                    {
                        ColorMap colorMap = new ColorMap();

                        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                        ColorMap[] remapTable = { colorMap };

                        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                        float transparency = 0.5F;
                        if (watermarkTransparency >= 1 && watermarkTransparency <= 100)
                        {
                            transparency = (watermarkTransparency / 100.0F);
                        }

                        float[][] colorMatrixElements = {
                                                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
                                            };

                        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

                        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                        int xpos = 0;
                        int ypos = 0;

                        switch (watermarkStatus)
                        {
                            case 1:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 2:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 3:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 4:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 5:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 6:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 7:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                            case 8:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                            case 9:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                        }

                        g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
                        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo ici = null;
                        foreach (ImageCodecInfo codec in codecs)
                        {
                            if (codec.MimeType.ToLower().IndexOf("jpeg") > -1 || codec.MimeType.ToLower().IndexOf("jpg") > -1)
                            {
                                ici = codec;
                            }
                        }
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[] qualityParam = new long[1];
                        if (quality < 0 || quality > 100)
                        {
                            quality = 80;
                        }
                        qualityParam[0] = quality;

                        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                        encoderParams.Param[0] = encoderParam;

                        if (ici != null)
                        {
                            img.Save(filename, ici, encoderParams);
                        }
                        else
                        {
                            img.Save(filename);
                        }

                        g.Dispose();
                        img.Dispose();
                        watermark.Dispose();
                        imageAttributes.Dispose();
                    }
                
            }
        }
        return true;
    }
    private void compress(System.Drawing.Image img, string path, string Extension)
    {
        try
        {
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L);

            ImageCodecInfo jpegCodec = null;
            if (Extension == ".jpeg")
            {
                jpegCodec = GetEncoderInfo("image/jpeg");
            }
            if (Extension == ".bmp")
            {
                jpegCodec = GetEncoderInfo("image/bmp");
            }
            if (Extension == ".gif")
            {
                jpegCodec = GetEncoderInfo("image/gif");
            }
            if (Extension == ".png")
            {
                jpegCodec = GetEncoderInfo("image/png");
            }
            if (Extension == ".jpg")
            {
                jpegCodec = GetEncoderInfo("image/jpeg");
            }
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int Width  = Convert.ToInt32(Request["Width"]);
                int Height = Convert.ToInt32(Request["Height"]);

                double   Lg_Full_Degree     = Convert.ToDouble(Request["Lg_Full_Degrees"]);
                double[] Planet_Full_Degree = new double[16] {
                    Convert.ToDouble(Request["Su_Full_Degrees"]), Convert.ToDouble(Request["Mo_Full_Degrees"]), Convert.ToDouble(Request["Ma_Full_Degrees"]), Convert.ToDouble(Request["Me_Full_Degrees"]), Convert.ToDouble(Request["Ju_Full_Degrees"]), Convert.ToDouble(Request["Ve_Full_Degrees"]), Convert.ToDouble(Request["Sa_Full_Degrees"]), Convert.ToDouble(Request["Ra_Full_Degrees"]), Convert.ToDouble(Request["Ke_Full_Degrees"]), Convert.ToDouble(Request["Ur_Full_Degrees"]), Convert.ToDouble(Request["Ne_Full_Degrees"]), Convert.ToDouble(Request["Pl_Full_Degrees"]), Convert.ToDouble(Request["Ch_Full_Degrees"]), Convert.ToDouble(Request["X_Full_Degrees"]), Convert.ToDouble(Request["Y_Full_Degrees"]), Convert.ToDouble(Request["Z_Full_Degrees"])
                };
                int[] Planet_Retro = new int[16] {
                    0, 0, Convert.ToInt32(Request["Ma_Retro"]), Convert.ToInt32(Request["Me_Retro"]), Convert.ToInt32(Request["Ju_Retro"]), Convert.ToInt32(Request["Ve_Retro"]), Convert.ToInt32(Request["Sa_Retro"]), 0, 0, Convert.ToInt32(Request["Ur_Retro"]), Convert.ToInt32(Request["Ne_Retro"]), Convert.ToInt32(Request["Pl_Retro"]), 0, 0, 0, 0
                };
                double birthTimeZone = Convert.ToDouble(Request["birthTimeZone"]);
                int    birthDST      = Convert.ToInt32(Request["birthDST"]);
                double birthJulDay   = Convert.ToDouble(Request["birthJulDay"]);
                string Name          = Request["Name"];

                //////////////////////////////////////

                int Lg_Sign = (int)Lg_Full_Degree / 30 + 1;
                if (Lg_Sign > 12)
                {
                    Lg_Sign -= 12;
                }
                double Lg_Degrees = (Lg_Full_Degree / 30 - (int)Lg_Full_Degree / 30) * 30;

                int[]    Planet_Signs   = new int[16];
                double[] Planet_Degrees = new double[16];

                int i = 0;
                for (i = 0; i < 16; i++)
                {
                    Planet_Signs[i] = (int)Planet_Full_Degree[i] / 30 + 1;
                    if (Planet_Signs[i] > 12)
                    {
                        Planet_Signs[i] -= 12;
                    }
                    Planet_Degrees[i] = (Planet_Full_Degree[i] / 30 - (int)Planet_Full_Degree[i] / 30) * 30;
                }

                //////////////////////////////////////


                // Set the page's content type to JPEG files
                // and clear all response headers.
                Response.ContentType = "image/jpeg";
                Response.Clear();

                // Buffer response so that page is sent
                // after processing is complete.
                Response.BufferOutput = true;

                Bitmap   objBitmap   = new Bitmap(Width, Height);
                Graphics objGraphics = Graphics.FromImage(objBitmap);
                objGraphics.SmoothingMode      = SmoothingMode.AntiAlias;
                objGraphics.CompositingQuality = CompositingQuality.HighQuality;
                objGraphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                objGraphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                objGraphics.TextRenderingHint  = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                objGraphics.Clear(Color.FromArgb(185, 208, 61));



                RectangleF chartRect = new RectangleF();


                float x1     = 0;
                float y1     = 0;
                float width  = Width / 2 - 30;
                float height = Width / 2 - 30;

                /****************************Planetary Details*******************************************/
                x1        = 20;
                y1        = 40;
                height    = Height - Width / 2 - 50;
                chartRect = new RectangleF(x1, y1, width, height);
                Functions.Draw_Table_Planetary_Details(objGraphics, chartRect, Planet_Degrees, Planet_Signs, Lg_Degrees, Lg_Sign, Planet_Retro);

                /***************************North Indian**********************************************/
                y1        = height + 60;
                height    = Width / 2 - 30;
                chartRect = new RectangleF(x1, y1, width, height);
                Functions.DrawChart_North(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Degrees, birthJulDay);

                /***************************RoundChart**********************************************/
                x1        = Width / 2 + 10;
                chartRect = new RectangleF(x1, y1, width, height);
                Functions.DrawChart_Round(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Degrees, birthJulDay);

                /***************************Table Combination********************************************/
                y1        = 40;
                height    = Height - Width - 40;
                chartRect = new RectangleF(x1, y1, width, height);
                Functions.Draw_Table_Combination(objGraphics, chartRect, Planet_Signs[0], Planet_Signs[1], Planet_Signs[3]);

                /*****************************South Indian***********************************************/
                y1        = y1 + height + 20;
                height    = Width / 2 - 30;
                chartRect = new RectangleF(x1, y1, width, height);
                Functions.DrawChart_South(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Degrees, birthJulDay);



                /*****************************South Indian***********************************************/
                //float x1 = 20;
                //float y1 = 20;
                //float width = Width / 2 - 30;
                //float height = Width / 2 - 30;

                //chartRect = new RectangleF(x1, y1, width, height);
                //Functions.DrawChart_South(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Retro, Planet_Degrees);

                ///***************************North Indian**********************************************/
                //x1 = Width / 2 + 10;
                //chartRect = new RectangleF(x1, y1, width, height);
                //Functions.DrawChart_North(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Retro, Planet_Degrees);


                ///***************************RoundChart**********************************************/
                //y1 = Width / 2 + 10;
                //chartRect = new RectangleF(x1, y1, width, height);
                //Functions.DrawChart_Round(objGraphics, chartRect, Lg_Sign, Planet_Signs, Planet_Retro, Planet_Degrees);

                ///***************************Table Combination********************************************/
                //y1 = Width + 10;
                //height = Height - Width - 30;
                //chartRect = new RectangleF(x1, y1, width, height);
                //Functions.Draw_Table_Combination(objGraphics, chartRect, Planet_Signs[0], Planet_Signs[1], Planet_Signs[3]);



                ///****************************Planetary Details*******************************************/
                //x1 = 20;
                //y1 = Width / 2 + 10;
                //height = Height - Width/2 - 30;
                //chartRect = new RectangleF(x1, y1, width, height);
                //Functions.Draw_Table_Planetary_Details(objGraphics, chartRect, Planet_Degrees, Planet_Signs, Lg_Degrees, Lg_Sign, Planet_Full_Degree, Lg_Full_Degree);


                ///////////////////////////////////////////////////////////////////////////////////

                SolidBrush fontBrush = new SolidBrush(Color.Black);

                StringFormat centerFormat = new StringFormat();
                centerFormat.Trimming      = StringTrimming.None;
                centerFormat.FormatFlags   = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
                centerFormat.LineAlignment = StringAlignment.Center;
                centerFormat.Alignment     = StringAlignment.Center;

                Font headFont = new Font("Times New Roman", 14, FontStyle.Bold);
                objGraphics.DrawString(Name, headFont, fontBrush, new RectangleF(0, 0, Width, 40), centerFormat);

                Font textFont = new Font("Verdana", 8);

                fontBrush.Color = Color.Firebrick;
                objGraphics.DrawString("© greenstonelobo.com", textFont, fontBrush, new RectangleF(Width / 2 + 10, Height - 15, Width / 2 - 30, 15), centerFormat);

                EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 100L);
                ImageCodecInfo   jpegCodec    = Functions.GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                objBitmap.Save(Response.OutputStream, jpegCodec, encoderParams);

                objGraphics.Dispose();
                objBitmap.Dispose();

                // Send the output to the client.
                Response.Flush();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
Beispiel #30
0
        public static void ProcessImage(Stream istm, Stream ostm, ProcessImageSettings s)
        {
            using (var img = Image.FromStream(istm, true, false))
            {
                if (s.FrameIndex > 0)
                {
                    var fd = img.RawFormat.Guid == ImageFormat.Gif.Guid ? FrameDimension.Time : FrameDimension.Page;
                    if (img.GetFrameCount(fd) > s.FrameIndex)
                    {
                        img.SelectActiveFrame(fd, s.FrameIndex);
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("Invalid Frame Index");
                    }
                }

                img.ExifRotate();

                s = s.Clone();
                s.Fixup(img.Width, img.Height);
                bool alpha = ((ImageFlags)img.Flags & ImageFlags.HasAlpha) == ImageFlags.HasAlpha;

                var src  = img;
                var crop = s.Crop;
                if (s.HybridScaleRatio > 1d)
                {
                    int intw = (int)Math.Ceiling(img.Width / s.HybridScaleRatio);
                    int inth = (int)Math.Ceiling(img.Height / s.HybridScaleRatio);

                    var bmp = new Bitmap(intw, inth);
                    using (var gfx = Graphics.FromImage(bmp))
                    {
                        gfx.PixelOffsetMode = PixelOffsetMode.Half;
                        gfx.CompositingMode = CompositingMode.SourceCopy;
                        gfx.DrawImage(img, Rectangle.FromLTRB(0, 0, intw, inth), crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel);
                    }

                    img.Dispose();
                    src  = bmp;
                    crop = new Rectangle(0, 0, intw, inth);
                }

                using (src)
                    using (var iat = new ImageAttributes())
                        using (var bmp = new Bitmap(s.Width, s.Height, alpha ? GdiPixelFormat.Format32bppArgb : GdiPixelFormat.Format24bppRgb))
                            using (var gfx = Graphics.FromImage(bmp))
                            {
                                iat.SetWrapMode(WrapMode.TileFlipXY);
                                gfx.PixelOffsetMode   = PixelOffsetMode.Half;
                                gfx.CompositingMode   = CompositingMode.SourceCopy;
                                gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

                                if (alpha && !s.MatteColor.IsEmpty)
                                {
                                    gfx.Clear(s.MatteColor);
                                    gfx.CompositingMode    = CompositingMode.SourceOver;
                                    gfx.CompositingQuality = CompositingQuality.GammaCorrected;
                                }

                                gfx.DrawImage(src, Rectangle.FromLTRB(0, 0, s.Width, s.Height), crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel, iat);

                                switch (s.SaveFormat)
                                {
                                case FileFormat.Bmp:
                                    bmp.Save(ostm, ImageFormat.Bmp);
                                    break;

                                case FileFormat.Tiff:
                                    using (var encoderParams = new EncoderParameters(1))
                                        using (var param = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone))
                                        {
                                            encoderParams.Param[0] = param;
                                            bmp.Save(ostm, tiffCodec, encoderParams);
                                        }
                                    break;

                                case FileFormat.Jpeg:
                                    using (var encoderParams = new EncoderParameters(1))
                                        using (var param = new EncoderParameter(Encoder.Quality, s.JpegQuality))
                                        {
                                            encoderParams.Param[0] = param;
                                            bmp.Save(ostm, jpegCodec, encoderParams);
                                        }
                                    break;

                                default:
                                    if (s.IndexedColor)
                                    {
                                        bmp.Save(ostm, ImageFormat.Gif);
                                    }
                                    else
                                    {
                                        bmp.Save(ostm, ImageFormat.Png);
                                    }
                                    break;
                                }
                            }
            }
        }
Beispiel #31
0
        internal static void Resize(string srcpath, string dstpath, string filename, int width, int height)
        {
            if (Path.GetFileName(filename) != filename)
            {
                throw new InvalidOperationException("'filename' is invalid!");
            }
            string combined_src  = Path.Combine(srcpath, filename);
            string filename_only = Path.GetFileNameWithoutExtension(filename);
            string combined_dst  = Path.Combine(dstpath, filename_only + ".jpeg");

            using (Tiff image = Tiff.Open(combined_src, "r"))
            {
                if (image == null)
                {
                    throw new InvalidOperationException("TIFF File not found");
                }

                //FieldValue[] exifIFDTag = image.GetField(TiffTag.EXIFIFD);
                //if (exifIFDTag == null)
                //{
                //    throw new InvalidOperationException("Exif metadata not found");
                //}

                //int exifIFDOffset = exifIFDTag[0].ToInt();
                //if (!image.ReadEXIFDirectory(exifIFDOffset))
                //{
                //    throw new InvalidOperationException("Could not read EXIF IFD");
                //}

                //image.SetDirectory(0);
                FieldValue[] value = image.GetField(TiffTag.IMAGEDESCRIPTION);
                value = image.GetField(TiffTag.IMAGEWIDTH);
                int _width = value[0].ToInt();

                value = image.GetField(TiffTag.IMAGELENGTH);
                int _height = value[0].ToInt();

                // Read the image into the memory buffer
                int[] raster = new int[_height * _width];
                if (!image.ReadRGBAImage(_width, _height, raster))
                {
                    throw new InvalidOperationException("Could not read Image");
                }
                using (Bitmap bmp = new Bitmap(_width, _height, PixelFormat.Format24bppRgb))
                {
                    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

                    BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    byte[]     bits    = new byte[bmpdata.Stride * bmpdata.Height];

                    for (int y = 0; y < bmp.Height; y++)
                    {
                        int rasterOffset = y * bmp.Width;
                        int bitsOffset   = (bmp.Height - y - 1) * bmpdata.Stride;

                        for (int x = 0; x < bmp.Width; x++)
                        {
                            int rgba = raster[rasterOffset++];
                            bits[bitsOffset++] = (byte)((rgba >> 16) & 0xff);
                            bits[bitsOffset++] = (byte)((rgba >> 8) & 0xff);
                            bits[bitsOffset++] = (byte)(rgba & 0xff);
                        }
                    }

                    System.Runtime.InteropServices.Marshal.Copy(bits, 0, bmpdata.Scan0, bits.Length);
                    bmp.UnlockBits(bmpdata);

                    int newWidth, newHeight;

                    if (bmp.Width > bmp.Height)
                    {
                        newWidth  = width;
                        newHeight = (int)(height * bmp.Height / bmp.Width);
                    }
                    else
                    {
                        newHeight = height;
                        newWidth  = (int)(width * bmp.Width / bmp.Height);
                    }

                    Rectangle destRect  = new Rectangle(0, 0, newWidth, newHeight);
                    Bitmap    destImage = new Bitmap(newWidth, newHeight);

                    destImage.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
                    using (var graphics = Graphics.FromImage(destImage))
                    {
                        graphics.CompositingMode    = CompositingMode.SourceCopy;
                        graphics.CompositingQuality = CompositingQuality.HighQuality;
                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        graphics.SmoothingMode      = SmoothingMode.HighQuality;
                        graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                        using (var wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            graphics.DrawImage(bmp, destRect, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, wrapMode);
                        }
                    }
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);

                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameter myEncoderParameter      = new EncoderParameter(myEncoder, 90L);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    destImage.Save(combined_dst, GetEncoder(ImageFormat.Jpeg), myEncoderParameters);
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="fontname">字体</param>
        /// <param name="fontsize">字体大小</param>
        public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            byte[] _ImageBytes = File.ReadAllBytes(GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = GetMapPath(filename);

            Graphics g        = Graphics.FromImage(img);
            Font     drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF    crSize;

            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (float)img.Width * (float).01;
                ypos = (float)img.Height * (float).01;
                break;

            case 2:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = (float)img.Height * (float).01;
                break;

            case 3:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = (float)img.Height * (float).01;
                break;

            case 4:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 5:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 6:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 7:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 8:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 9:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
        }
Beispiel #33
0
        protected byte[] ProcessProfilePicture(byte[] bytes)
        {
            Bitmap image;

            using (System.IO.MemoryStream m = new System.IO.MemoryStream(bytes))
            {
                image = new Bitmap(Image.FromStream(m));
            }
            if (image != null)
            {
                int size = 640;
                if (size > image.Width)
                {
                    size = image.Width;
                }
                if (size > image.Height)
                {
                    size = image.Height;
                }

                int   newHeight = 0;
                int   newWidth  = 0;
                float imgWidth  = float.Parse(image.Width.ToString());
                float imgHeight = float.Parse(image.Height.ToString());
                if (image.Width < image.Height)
                {
                    newHeight = (int)((imgHeight / imgWidth) * size);
                    newWidth  = size;
                }
                else
                {
                    newWidth  = (int)((imgWidth / imgHeight) * size);
                    newHeight = size;
                }

                Bitmap newImage = new Bitmap(newWidth, newHeight);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    gr.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight));
                }

                //crop square
                Bitmap dest = newImage.Clone(new Rectangle(
                                                 new Point(0, 0),
                                                 new Size(size, size)
                                                 ), image.PixelFormat);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters encParams        = new EncoderParameters(1);

                EncoderParameter param = new EncoderParameter(enc, 50L);
                encParams.Param[0] = param;
                dest.Save(ms, GetEncoder(ImageFormat.Jpeg), encParams);
                ms.Close();
                return(ms.ToArray());
            }
            return(bytes);
        }
Beispiel #34
0
        public bool SaveMultipage(List <ScannedImage> images, string location, Func <int, bool> progressCallback)
        {
            try
            {
                ImageCodecInfo codecInfo = GetCodecForString("TIFF");

                if (!progressCallback(0))
                {
                    return(false);
                }

                PathHelper.EnsureParentDirExists(location);

                if (images.Count == 1)
                {
                    var     iparams    = new EncoderParameters(1);
                    Encoder iparam     = Encoder.Compression;
                    var     iparamPara = new EncoderParameter(iparam, (long)(EncoderValue.CompressionLZW));
                    iparams.Param[0] = iparamPara;
                    using (var bitmap = scannedImageRenderer.Render(images[0]))
                    {
                        bitmap.Save(location, codecInfo, iparams);
                    }
                }
                else if (images.Count > 1)
                {
                    Encoder          saveEncoder;
                    Encoder          compressionEncoder;
                    EncoderParameter SaveEncodeParam;
                    EncoderParameter CompressionEncodeParam;
                    var encoderParams = new EncoderParameters(2);

                    saveEncoder        = Encoder.SaveFlag;
                    compressionEncoder = Encoder.Compression;

                    // Save the first page (frame).
                    SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame);
                    CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionLZW);
                    encoderParams.Param[0] = CompressionEncodeParam;
                    encoderParams.Param[1] = SaveEncodeParam;

                    File.Delete(location);
                    using (var bitmap0 = scannedImageRenderer.Render(images[0]))
                    {
                        bitmap0.Save(location, codecInfo, encoderParams);

                        for (int i = 1; i < images.Count; i++)
                        {
                            if (images[i] == null)
                            {
                                break;
                            }

                            if (!progressCallback(i))
                            {
                                bitmap0.Dispose();
                                File.Delete(location);
                                return(false);
                            }

                            SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage);
                            CompressionEncodeParam = new EncoderParameter(compressionEncoder,
                                                                          (long)EncoderValue.CompressionLZW);
                            encoderParams.Param[0] = CompressionEncodeParam;
                            encoderParams.Param[1] = SaveEncodeParam;
                            using (var bitmap = scannedImageRenderer.Render(images[i]))
                            {
                                bitmap0.SaveAdd(bitmap, encoderParams);
                            }
                        }

                        SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush);
                        encoderParams.Param[0] = SaveEncodeParam;
                        bitmap0.SaveAdd(encoderParams);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception("Error saving TIFF", ex);
            }
        }
Beispiel #35
0
        /// <summary>
        /// 上传图片并生成略缩图
        /// </summary>
        /// <param name="files">FileUpload控件</param>
        /// <returns></returns>
        public static void ImageUpLoad(FileUpload files, Int32 ThumbnailWidth, Int32 ThumbnailHeight, ref string picpath, ref string smallpicpath)
        {
            //System.Drawing.Image xImage;
            System.Drawing.Bitmap xBitmap;
            int PhotoHeight, PhotoWidth;

            //Rectangle NewPhoto;
            System.Drawing.Imaging.ImageFormat xObject;
            string smallFileName = "";
            string smallSaveFile = "";

            picpath      = "";
            smallpicpath = "";
            if (files.FileName != "")
            {
                string ext = EKFileUpload.getExtend(files.FileName);
                ext = ext.ToLower();
                if (ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "bmp" || ext == "png")
                {
                    long FLength = files.PostedFile.ContentLength / 1024;
                    if (FLength > MS_ConfigBLL.UploadSize)
                    {
                        EKMessageBox.Show("文件上传失败!因为上传的文件超过了" + MS_ConfigBLL.UploadSize + "KB!");
                    }
                    else
                    {
                        string createfilename = EKFileUpload.createFileName();
                        string FileName       = "/" + MS_ConfigBLL.UploadPath + "/" + EKFileUpload.getMyPath() + createfilename + "." + ext;
                        string SaveFile       = EKFileUpload.FilePath + FileName;
                        EKFileUpload.doCreatrDir(SaveFile);
                        files.SaveAs(SaveFile);
                        picpath = FileName;

                        smallFileName = "/" + MS_ConfigBLL.UploadPath + "/" + EKFileUpload.getMyPath() + "small" + createfilename + "." + ext;
                        smallSaveFile = EKFileUpload.FilePath + smallFileName;
                        switch (ext)
                        {
                        case ".gif":
                            xObject = System.Drawing.Imaging.ImageFormat.Gif;
                            break;

                        case ".bmp":
                            xObject = System.Drawing.Imaging.ImageFormat.Bmp;
                            break;

                        case ".png":
                            xObject = System.Drawing.Imaging.ImageFormat.Png;
                            break;

                        default:
                            xObject = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;
                        }

                        xBitmap = new Bitmap(SaveFile);//------------------

                        PhotoHeight = xBitmap.Height;
                        PhotoWidth  = xBitmap.Width;
                        Int32 TempHeight = 0;
                        Int32 TempWidth  = 0;
                        if (PhotoWidth <= ThumbnailWidth && PhotoHeight <= ThumbnailHeight)
                        {
                            EKFileUpload.doCreatrDir(smallSaveFile);
                            xBitmap.Save(smallSaveFile);
                        }
                        else
                        {
                            if (PhotoWidth > ThumbnailWidth)//图片宽度大于设定宽度
                            {
                                TempWidth  = ThumbnailWidth;
                                TempHeight = Convert.ToInt32(Convert.ToDecimal(PhotoHeight) / Convert.ToDecimal(PhotoWidth) * Convert.ToDecimal(ThumbnailWidth));
                                if (TempHeight > ThumbnailHeight)
                                {
                                    TempWidth  = Convert.ToInt32(Convert.ToDecimal(TempWidth) / Convert.ToDecimal(TempHeight) * Convert.ToDecimal(ThumbnailHeight));
                                    TempHeight = ThumbnailHeight;
                                }
                            }
                            else
                            {
                                if (PhotoHeight > ThumbnailHeight)
                                {
                                    TempHeight = ThumbnailHeight;
                                    TempWidth  = Convert.ToInt32(Convert.ToDecimal(PhotoWidth) / Convert.ToDecimal(PhotoHeight) * Convert.ToDecimal(ThumbnailHeight));
                                }
                            }
                            //System.Web.HttpContext.Current.Response.Write(TempHeight.ToString()+",");
                            //System.Web.HttpContext.Current.Response.Write(TempWidth.ToString());
                            //System.Web.HttpContext.Current.Response.End();
                            if (TempHeight <= 0)
                            {
                                TempHeight = 1;
                            }
                            if (TempWidth <= 0)
                            {
                                TempWidth = 1;
                            }

                            System.Drawing.Image bitmap = new System.Drawing.Bitmap(TempWidth, TempHeight);
                            //新建一个画板
                            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                            //设置高质量插值法
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            //设置高质量,低速度呈现平滑程度
                            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            //清空一下画布
                            g.Clear(Color.Empty);
                            //在指定位置画图
                            g.DrawImage(xBitmap, new System.Drawing.Rectangle(0, 0, TempWidth, TempHeight), new System.Drawing.Rectangle(1, 1, xBitmap.Width - 1, xBitmap.Height - 1), System.Drawing.GraphicsUnit.Pixel);

                            // 以下代码为保存图片时,设置压缩质量
                            EncoderParameters encoderParams = new EncoderParameters();
                            long[]            quality       = new long[1];
                            quality[0] = 95;
                            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                            encoderParams.Param[0] = encoderParam;
                            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                            ImageCodecInfo   jpegICI  = null;
                            for (int x = 0; x < arrayICI.Length; x++)
                            {
                                if (arrayICI[x].FormatDescription.Equals("jpeg"))
                                {
                                    jpegICI = arrayICI[x];
                                    //设置JPEG编码
                                    break;
                                }
                            }
                            if (jpegICI != null)
                            {
                                //System.Web.HttpContext.Current.Response.Write("a");
                                EKFileUpload.doCreatrDir(smallSaveFile);
                                bitmap.Save(smallSaveFile, jpegICI, encoderParams);
                            }
                            else
                            {
                                //System.Web.HttpContext.Current.Response.Write("b");
                                EKFileUpload.doCreatrDir(smallSaveFile);
                                bitmap.Save(smallSaveFile, xObject);
                            }
                            bitmap.Dispose();
                        }
                        xBitmap.Dispose();
                    }
                    smallpicpath = smallFileName;
                }
                else
                {
                    EKMessageBox.Show("文件上传失败,因为文件格式不允许上传!");
                    return;
                }
            }
        }
Beispiel #36
0
 /// <summary>
 /// 压缩到指定尺寸
 /// </summary>
 /// <param name="oldfile">原文件</param>
 /// <param name="newfile">新文件</param>
 public bool Compress(string oldfile, string newfile)
 {
     try
     {
         System.Drawing.Image img = System.Drawing.Image.FromFile(oldfile);
         System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
         Size newSize = new Size(100, 125);
         Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
         Graphics g = Graphics.FromImage(outBmp);
         g.CompositingQuality = CompositingQuality.HighQuality;
         g.SmoothingMode = SmoothingMode.HighQuality;
         g.InterpolationMode = InterpolationMode.HighQualityBicubic;
         g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
         g.Dispose();
         EncoderParameters encoderParams = new EncoderParameters();
         long[] quality = new long[1];
         quality[0] = 100;
         EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
         encoderParams.Param[0] = encoderParam;
         ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
         ImageCodecInfo jpegICI = null;
         for (int x = 0; x < arrayICI.Length; x++)
             if (arrayICI[x].FormatDescription.Equals("JPEG"))
             {
                 jpegICI = arrayICI[x]; //设置JPEG编码
                 break;
             }
         img.Dispose();
         if (jpegICI != null) outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
         outBmp.Dispose();
         return true;
     }
     catch
     {
         return false;
     }
 }
Beispiel #37
0
        /// <summary>
        /// 上传略缩图并添加水印
        /// </summary>
        /// <param name="files">FileUpload控件</param>
        /// <returns></returns>
        public static void ImageUpLoad(FileUpload files, Int32 Width, Int32 Height, Watermark watermark, ref string picpath)
        {
            //System.Drawing.Image xImage;
            System.Drawing.Bitmap xBitmap;
            int PhotoHeight, PhotoWidth;

            //Rectangle NewPhoto;
            System.Drawing.Imaging.ImageFormat xObject;
            picpath = "";

            if (files.FileName != "")
            {
                string ext = EKFileUpload.getExtend(files.FileName);
                ext = ext.ToLower();
                if (ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "bmp" || ext == "png")
                {
                    long FLength = files.PostedFile.ContentLength / 1024;
                    if (FLength > MS_ConfigBLL.UploadSize)
                    {
                        EKMessageBox.Show("文件上传失败!因为上传的文件超过了" + MS_ConfigBLL.UploadSize + "KB!");
                    }
                    else
                    {
                        string createfilename = EKFileUpload.createFileName();
                        string FileName       = "/" + MS_ConfigBLL.UploadPath + "/" + EKFileUpload.getMyPath() + createfilename + "." + ext;
                        string SaveFile       = EKFileUpload.FilePath + FileName;
                        //EKFileUpload.doCreatrDir(SaveFile);
                        //files.SaveAs(SaveFile);
                        picpath = FileName.Replace("//", "/");

                        switch (ext)
                        {
                        case ".gif":
                            xObject = System.Drawing.Imaging.ImageFormat.Gif;
                            break;

                        case ".bmp":
                            xObject = System.Drawing.Imaging.ImageFormat.Bmp;
                            break;

                        case ".png":
                            xObject = System.Drawing.Imaging.ImageFormat.Png;
                            break;

                        default:
                            xObject = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;
                        }

                        xBitmap = new Bitmap(files.FileContent);//------------------

                        PhotoHeight = xBitmap.Height;
                        PhotoWidth  = xBitmap.Width;
                        Int32 TempHeight = 0;
                        Int32 TempWidth  = 0;
                        if (PhotoWidth <= Width && PhotoHeight <= Height)
                        {
                            TempWidth  = PhotoWidth;
                            TempHeight = PhotoHeight;
                        }
                        else
                        {
                            if (PhotoWidth > Width)//图片宽度大于设定宽度
                            {
                                TempWidth  = Width;
                                TempHeight = Convert.ToInt32(Convert.ToDecimal(PhotoHeight) / Convert.ToDecimal(PhotoWidth) * Convert.ToDecimal(Width));
                                if (TempHeight > Height)
                                {
                                    TempWidth  = Convert.ToInt32(Convert.ToDecimal(TempWidth) / Convert.ToDecimal(TempHeight) * Convert.ToDecimal(Height));
                                    TempHeight = Height;
                                }
                            }
                            else
                            {
                                if (PhotoHeight > Height)
                                {
                                    TempHeight = Height;
                                    TempWidth  = Convert.ToInt32(Convert.ToDecimal(PhotoWidth) / Convert.ToDecimal(PhotoHeight) * Convert.ToDecimal(Height));
                                }
                            }
                            //System.Web.HttpContext.Current.Response.Write(TempHeight.ToString()+",");
                            //System.Web.HttpContext.Current.Response.Write(TempWidth.ToString());
                            //System.Web.HttpContext.Current.Response.End();
                            if (TempHeight <= 0)
                            {
                                TempHeight = 1;
                            }
                            if (TempWidth <= 0)
                            {
                                TempWidth = 1;
                            }
                        }

                        System.Drawing.Image bitmap = new System.Drawing.Bitmap(TempWidth, TempHeight);
                        //新建一个画板
                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                        //设置高质量插值法
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        //设置高质量,低速度呈现平滑程度
                        g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //清空一下画布
                        g.Clear(Color.Empty);
                        //在指定位置画图
                        g.DrawImage(xBitmap, new System.Drawing.Rectangle(0, 0, TempWidth, TempHeight), new System.Drawing.Rectangle(1, 1, xBitmap.Width - 1, xBitmap.Height - 1), System.Drawing.GraphicsUnit.Pixel);

                        //添加水印
                        if (watermark != null)
                        {
                            if (watermark.MarkType == "text")
                            {
                                //声明字体对象
                                Font cFont = null;
                                //用来测试水印文本长度得尺子
                                SizeF size = new SizeF();

                                int[] sizes = new int[] { watermark.Size, 48, 32, 16, 8, 6, 4 };

                                //探测出一个适合图片大小得字体大小,以适应水印文字大小得自适应
                                for (int i = 0; i < 7; i++)
                                {
                                    if (sizes[i] == 0)
                                    {
                                        continue;
                                    }
                                    //创建一个字体对象
                                    cFont = new Font(watermark.FontFamily, sizes[i], FontStyle.Regular);
                                    //是否加粗、倾斜
                                    if (watermark.TextBlod && watermark.TextItalic)
                                    {
                                        cFont = new Font(watermark.FontFamily, sizes[i], FontStyle.Bold | FontStyle.Italic);
                                    }
                                    else if (watermark.TextBlod)
                                    {
                                        cFont = new Font(watermark.FontFamily, sizes[i], FontStyle.Bold);
                                    }
                                    else if (watermark.TextItalic)
                                    {
                                        cFont = new Font(watermark.FontFamily, sizes[i], FontStyle.Italic);
                                    }

                                    //测量文本大小
                                    size = g.MeasureString(watermark.Text, cFont);
                                    //匹配第一个符合要求得字体大小
                                    if ((ushort)size.Width < (ushort)TempWidth)
                                    {
                                        break;
                                    }
                                }

                                Brush brush = new SolidBrush(Color.FromArgb(Convert.ToInt32(watermark.Transparency * 255), watermark.TextColor));

                                //添加水印 文字
                                g.DrawString(watermark.Text, cFont, brush, watermark.Position(watermark.Place, new SizeF(TempWidth, TempHeight), size));
                            }
                            else if (watermark.MarkType == "image")
                            {
                                //获得水印图像
                                System.Drawing.Image markImg = System.Drawing.Image.FromFile(EKFileUpload.FilePath + watermark.ImgPath);

                                //创建颜色矩阵
                                float[][] ptsArray =
                                {
                                    new float[] { 1, 0, 0,                      0, 0 },
                                    new float[] { 0, 1, 0,                      0, 0 },
                                    new float[] { 0, 0, 1,                      0, 0 },
                                    new float[] { 0, 0, 0, watermark.Transparency, 0 },                  //注意:此处为0.0f为完全透明,1.0f为完全不透明
                                    new float[] { 0, 0, 0,                      0, 1 }
                                };
                                ColorMatrix colorMatrix = new ColorMatrix(ptsArray);
                                //新建一个Image属性
                                ImageAttributes imageAttributes = new ImageAttributes();
                                //将颜色矩阵添加到属性
                                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default,
                                                               ColorAdjustType.Default);

                                //原图过小
                                if (markImg.Width > TempWidth || markImg.Height > TempHeight)
                                {
                                    System.Drawing.Image.GetThumbnailImageAbort callb = null;
                                    //对水印图片生成缩略图,缩小到原图得1/4
                                    System.Drawing.Image new_img = markImg.GetThumbnailImage(TempWidth / 4, markImg.Height * TempWidth / 4 / markImg.Width, callb, new System.IntPtr());

                                    //添加水印图片
                                    g.DrawImage(new_img, watermark.Position(watermark.Place, new Size(TempWidth, TempHeight), new_img.Size), 0, 0, new_img.Width, new_img.Height, GraphicsUnit.Pixel, imageAttributes);
                                    //释放缩略图
                                    new_img.Dispose();
                                }
                                else
                                {
                                    //添加水印图片
                                    g.DrawImage(markImg, watermark.Position(watermark.Place, new Size(TempWidth, TempHeight), markImg.Size), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes);
                                }
                            }
                        }

                        // 以下代码为保存图片时,设置压缩质量
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[]            quality       = new long[1];
                        quality[0] = 95;
                        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                        encoderParams.Param[0] = encoderParam;
                        //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo   jpegICI  = null;
                        for (int x = 0; x < arrayICI.Length; x++)
                        {
                            if (arrayICI[x].FormatDescription.Equals("jpeg"))
                            {
                                jpegICI = arrayICI[x];
                                //设置JPEG编码
                                break;
                            }
                        }
                        if (jpegICI != null)
                        {
                            //System.Web.HttpContext.Current.Response.Write("a");
                            EKFileUpload.doCreatrDir(SaveFile);
                            bitmap.Save(SaveFile, jpegICI, encoderParams);
                        }
                        else
                        {
                            //System.Web.HttpContext.Current.Response.Write("b");
                            EKFileUpload.doCreatrDir(SaveFile);
                            bitmap.Save(SaveFile, xObject);
                        }
                        g.Dispose();

                        bitmap.Dispose();

                        xBitmap.Dispose();
                    }
                }
                //picpath = FileName;
            }
            else
            {
                EKMessageBox.Show("文件上传失败,因为文件格式不允许上传!");
                return;
            }
        }
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>

        public static bool GetPicThumbnail(string sFile, string dFile, ref string errMsg, int dHeight = 0, int dWidth = 0, int flag = 60)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);

            ImageFormat tFormat = iSource.RawFormat;

            int sW = 0, sH = 0;

            //按比例缩放

            Size tem_size = new Size(iSource.Width, iSource.Height);

            dHeight = dHeight == 0 ? tem_size.Height : dHeight;
            dWidth  = dWidth == 0 ? tem_size.Width : dWidth;
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }

                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }

            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap   ob = new Bitmap(dWidth, dHeight);
            Graphics g  = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }


                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch (Exception ex)
            {
                errMsg = ex.Message + ",堆栈:" + ex.StackTrace + "InnerException:" + ex.InnerException;
                return(false);
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
Beispiel #39
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="filePath">源路径</param>
        /// <param name="smallSaveFile">目标路径</param>
        /// <param name="ThumbnailWidth">缩略图宽</param>
        /// <param name="ThumbnailHeight">缩略图高</param>
        public static void ImageUpLoad(string filePath, string smallSaveFile, Int32 ThumbnailWidth, Int32 ThumbnailHeight)
        {
            System.Drawing.Bitmap xBitmap;
            int PhotoHeight, PhotoWidth;

            System.Drawing.Imaging.ImageFormat xObject;
            if (filePath != "")
            {
                string ext = EKFileUpload.getExtend(filePath);
                ext = ext.ToLower();
                if (ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "bmp" || ext == "png")
                {
                    switch (ext)
                    {
                    case ".gif":
                        xObject = System.Drawing.Imaging.ImageFormat.Gif;
                        break;

                    case ".bmp":
                        xObject = System.Drawing.Imaging.ImageFormat.Bmp;
                        break;

                    case ".png":
                        xObject = System.Drawing.Imaging.ImageFormat.Png;
                        break;

                    default:
                        xObject = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;
                    }

                    xBitmap = new Bitmap(filePath);

                    PhotoHeight = xBitmap.Height;
                    PhotoWidth  = xBitmap.Width;
                    Int32 TempHeight = 0;
                    Int32 TempWidth  = 0;
                    if (PhotoWidth <= ThumbnailWidth && PhotoHeight <= ThumbnailHeight)
                    {
                        EKFileUpload.doCreatrDir(smallSaveFile);
                        xBitmap.Save(smallSaveFile);
                    }
                    else
                    {
                        if (PhotoWidth > ThumbnailWidth)//图片宽度大于设定宽度
                        {
                            TempWidth  = ThumbnailWidth;
                            TempHeight = Convert.ToInt32(Convert.ToDecimal(PhotoHeight) / Convert.ToDecimal(PhotoWidth) * Convert.ToDecimal(ThumbnailWidth));
                            if (TempHeight > ThumbnailHeight)
                            {
                                TempWidth  = Convert.ToInt32(Convert.ToDecimal(TempWidth) / Convert.ToDecimal(TempHeight) * Convert.ToDecimal(ThumbnailHeight));
                                TempHeight = ThumbnailHeight;
                            }
                        }
                        else
                        {
                            if (PhotoHeight > ThumbnailHeight)
                            {
                                TempHeight = ThumbnailHeight;
                                TempWidth  = Convert.ToInt32(Convert.ToDecimal(PhotoWidth) / Convert.ToDecimal(PhotoHeight) * Convert.ToDecimal(ThumbnailHeight));
                            }
                        }
                        if (TempHeight <= 0)
                        {
                            TempHeight = 1;
                        }
                        if (TempWidth <= 0)
                        {
                            TempWidth = 1;
                        }

                        System.Drawing.Image bitmap = new System.Drawing.Bitmap(TempWidth, TempHeight);
                        //新建一个画板
                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                        //设置高质量插值法
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        //设置高质量,低速度呈现平滑程度
                        g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //清空一下画布
                        g.Clear(Color.Empty);
                        //在指定位置画图
                        g.DrawImage(xBitmap, new System.Drawing.Rectangle(0, 0, TempWidth, TempHeight), new System.Drawing.Rectangle(1, 1, xBitmap.Width - 1, xBitmap.Height - 1), System.Drawing.GraphicsUnit.Pixel);

                        // 以下代码为保存图片时,设置压缩质量
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[]            quality       = new long[1];
                        quality[0] = 80;
                        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                        encoderParams.Param[0] = encoderParam;
                        //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo   jpegICI  = null;
                        for (int x = 0; x < arrayICI.Length; x++)
                        {
                            if (arrayICI[x].FormatDescription.Equals("jpeg"))
                            {
                                jpegICI = arrayICI[x];
                                //设置JPEG编码
                                break;
                            }
                        }
                        if (jpegICI != null)
                        {
                            //System.Web.HttpContext.Current.Response.Write("a");
                            EKFileUpload.doCreatrDir(smallSaveFile);
                            bitmap.Save(smallSaveFile, jpegICI, encoderParams);
                        }
                        else
                        {
                            //System.Web.HttpContext.Current.Response.Write("b");
                            EKFileUpload.doCreatrDir(smallSaveFile);
                            xBitmap.Dispose();
                            bitmap.Save(smallSaveFile, xObject);
                        }
                        bitmap.Dispose();
                    }
                    xBitmap.Dispose();
                }
                else
                {
                    //格式不对
                }
            }
        }
Beispiel #40
0
    /// <summary>
    /// 无损压缩图片
    /// </summary>
    /// <param name="sFile">原图片</param>
    /// <param name="dFile">压缩后保存位置</param>
    /// <param name="height">高度</param>
    /// <param name="width"></param>
    /// <param name="flag">压缩质量 1-100</param>
    /// <param name="type">压缩缩放类型</param>
    /// <returns></returns>
    public bool Thumbnail(string sFile, string dFile, int height, int width, int flag, ImgThumbnailType type)
    {
        System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
        ImageFormat tFormat = iSource.RawFormat;

        //缩放后的宽度和高度
        int towidth = width;
        int toheight = height;
        //
        int x = 0;
        int y = 0;
        int ow = iSource.Width;
        int oh = iSource.Height;

        switch (type)
        {
            case ImgThumbnailType.WH://指定高宽缩放(可能变形)
                {
                    break;
                }
            case ImgThumbnailType.W://指定宽,高按比例
                {
                    toheight = iSource.Height * width / iSource.Width;
                    break;
                }
            case ImgThumbnailType.H://指定高,宽按比例
                {
                    towidth = iSource.Width * height / iSource.Height;
                    break;
                }
            case ImgThumbnailType.Cut://指定高宽裁减(不变形)
                {
                    if ((double)iSource.Width / (double)iSource.Height > (double)towidth / (double)toheight)
                    {
                        oh = iSource.Height;
                        ow = iSource.Height * towidth / toheight;
                        y = 0;
                        x = (iSource.Width - ow) / 2;
                    }
                    else
                    {
                        ow = iSource.Width;
                        oh = iSource.Width * height / towidth;
                        x = 0;
                        y = (iSource.Height - oh) / 2;
                    }
                    break;
                }
            default:
                break;
        }

        Bitmap ob = new Bitmap(towidth, toheight);
        Graphics g = Graphics.FromImage(ob);
        g.Clear(System.Drawing.Color.WhiteSmoke);
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(iSource
          , new Rectangle(x, y, towidth, toheight)
          , new Rectangle(0, 0, iSource.Width, iSource.Height)
          , GraphicsUnit.Pixel);
        g.Dispose();
        //以下代码为保存图片时,设置压缩质量
        EncoderParameters ep = new EncoderParameters();
        long[] qy = new long[1];
        qy[0] = flag;//设置压缩的比例1-100
        EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
        ep.Param[0] = eParam;
        try
        {
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICIinfo = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICIinfo = arrayICI[i];
                    break;
                }
            }
            if (jpegICIinfo != null)
            {
                ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
            }
            else
            {
                ob.Save(dFile, tFormat);
            }
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            iSource.Dispose();

            ob.Dispose();

        }
    }
    public MemoryStream BmpToJpeg(Image bmp)
    {
        var qualityEncoder = Encoder.Quality;
        const int quality = 100;
        var ratio = new EncoderParameter(qualityEncoder, quality);
        var codecParams = new EncoderParameters(1);
        codecParams.Param[0] = ratio;
        var jpegCodecInfo = GetEncoder(ImageFormat.Jpeg);

        var ms = new MemoryStream();
        bmp.Save(ms, jpegCodecInfo, codecParams);
        return ms;
    }
    /// <summary>
    /// To create new image with new dimensions.
    /// </summary>
    /// <param name="smallImgPath">Source Img</param>
    /// <param name="bigImgPath">Destination Img</param>
    /// <param name="width">New Width</param>
    /// <param name="height">New Height</param>
    private void SaveThumbnail(string smallImgPath, string bigImgPath, int width, int height)
    {
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters=new EncoderParameters();
        ImageCodecInfo myImageCodecInfo;
        // Get an ImageCodecInfo object that represents the JPEG codec.
        myImageCodecInfo = GetEncoderInfo("image/png");
        System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        Bitmap myBitmap = new Bitmap(smallImgPath);
        // for the Quality parameter category.
        myEncoder = Encoder.Quality;
        // Save the bitmap as a JPEG file with quality level 50.
        myEncoderParameter = new EncoderParameter(myEncoder, 100L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        int imageHeight = (int)((width * myBitmap.Height) / myBitmap.Width);
        int imageWidth = (int)((height * myBitmap.Width) / myBitmap.Height);
        System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(imageWidth, height, myCallback, IntPtr.Zero);

        myThumbnail.Save(bigImgPath, myImageCodecInfo, myEncoderParameters);
        myBitmap.Dispose();
        myThumbnail.Dispose();
    }
Beispiel #43
0
 public EncoderParameters()
 {
     Param = new EncoderParameter[1];
 }
Beispiel #44
0
    private static void SaveImage(Bitmap bmp, string path)
    {
        var jgpEncoder = GetEncoder(ImageFormat.Png);


        var myEncoder = System.Drawing.Imaging.Encoder.Quality;
        var myEncoderParameters = new EncoderParameters(1);

        var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        bmp.Save(path, jgpEncoder, myEncoderParameters);
        GC.Collect();
    }
Beispiel #45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            double proporcao;
            int w, h, xCrop, yCrop;
            string imgName = Request.QueryString["img"];
            byte crop = Convert.ToByte(Request.QueryString["c"]);
            string colorName = Request.QueryString["b"];
            int interpolationMode = Convert.ToInt16(Request.QueryString["i"]);

            //Precisão do redimensionamento
            int p = Convert.ToInt32(Request.QueryString["p"]);

            int widthT = Convert.ToInt32(Request.QueryString["w"]);
            int heightT = Convert.ToInt32(Request.QueryString["h"]);

            //Nome da imagem a ser cacheada ou comparada
            string strImg = imgName.Substring(0, imgName.LastIndexOf('.')) + "_" + widthT + "x" + heightT + "_" + crop.ToString() + (string.IsNullOrEmpty(colorName) ? "" : "_" + colorName) + "_" + interpolationMode + "_" + p + imgName.Substring(imgName.LastIndexOf('.'));

            //Path com as imagens "cacheadas"
            string cachePath = Path.Combine(Server.MapPath("~/Arquivos/ThumbCache/"), strImg);

            //Dados da última
            DateTime dataModCache = File.GetLastWriteTime(Server.MapPath(imgName));
            DateTime dataModImg = File.GetLastWriteTime(cachePath);

            int comparacao = DateTime.Compare(dataModCache, dataModImg);

            //Se o arquivo já existe no cache
            if (File.Exists(cachePath) && comparacao <= 0)
            {
                OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(cachePath));
                HttpContext.Current.Response.WriteFile(cachePath);
                return;
            }
            else
            {

                //Cria diretório com as imagens (parâmetro)
                Directory.CreateDirectory(Path.GetDirectoryName(cachePath));

                //Deleta se já existe imagem cacheada
                if (File.Exists(cachePath))
                {
                    File.Delete(cachePath);
                }

                //Cria o "bitmap" com imagem original
                string imgPath = HttpContext.Current.Request.MapPath("~/" + imgName);
                Bitmap bmp = new Bitmap(imgPath);
                ImageFormat formato = bmp.RawFormat;
                double widthO = bmp.Size.Width;
                double heightO = bmp.Size.Height;

                //Caso só largura ou altura sejam transmitidas
                if (widthT == 0 || heightT == 0)
                {
                    //Cálculo com base na largura (widthT)
                    if (widthT > 0)
                    {
                        heightO = widthT / (widthO / heightO);
                        widthO = widthT;
                        heightT = Convert.ToInt32(heightO);
                        //Cálculo com base na altura (heightT)
                    }
                    else
                    {
                        widthO = heightT / (heightO / widthO);
                        heightO = heightT;
                        widthT = Convert.ToInt32(widthO);
                    }
                }
                else
                {
                    //Caso opção seja "CROPAR"
                    if (crop == 1)
                    {
                        //Se uma das medidas originais forem MAIORES que o "Target"
                        if (widthO > widthT || heightO > heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO > widthT || heightO > heightT)
                            {
                                widthO--;
                                heightO = widthO / proporcao;
                                if (widthO <= widthT && heightO <= heightT)
                                {
                                    break;
                                }
                            }
                        }
                        //Se uma das medidas originais forem MENORES que o "Target"
                        if (widthO < widthT || heightO < heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO < widthT || heightO < heightT)
                            {
                                widthO++;
                                heightO = widthO / proporcao;
                                if (widthO >= widthT && heightO >= heightT)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        //Se uma das medidas originais forem MAIORES que o "Target"
                        if (widthO > widthT || heightO > heightT)
                        {
                            proporcao = widthO / heightO;
                            while (widthO > widthT || heightO > heightT)
                            {
                                widthO--;
                                heightO = widthO / proporcao;
                                if (widthO <= widthT && heightO <= heightT)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            //Se uma das medidas originais forem MENORES que o "Target"
                            if (widthO < widthT || heightO < heightT)
                            {
                                proporcao = widthO / heightO;
                                while (widthO < widthT && heightO < heightT)
                                {
                                    widthO++;
                                    heightO = widthO / proporcao;
                                    if (widthO >= widthT && heightO >= heightT)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                //Medidas finais (incluindo valor de precisão)
                w = Convert.ToInt32(widthO) + p;
                h = Convert.ToInt32(heightO) + p;

                //Calcula as coordenadas para corte
                xCrop = Convert.ToInt32((w - widthT) / 2);
                yCrop = Convert.ToInt32((h - heightT) / 2);

                Bitmap bmpT = new Bitmap(widthT, heightT);

                EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 95L);
                //Image codec
                ImageCodecInfo imgCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.FormatID == formato.Guid);
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                //Cor de fundo
                Color bg = Color.White;

                //Caso a cor não seja transmitida
                if (string.IsNullOrEmpty(colorName))
                {
                    //se PNG "transparent"
                    if (formato.Equals(ImageFormat.Png) || formato.Equals(ImageFormat.Gif))
                        bg = Color.Transparent;
                }
                else
                {
                    try
                    {
                        //Html color (hex)
                        bg = ColorTranslator.FromHtml("#" + colorName);
                    }
                    catch (Exception)
                    {
                        //Html color
                        bg = ColorTranslator.FromHtml(colorName);
                    }
                }

                //Manipula e salva em cache
                using (Graphics g = Graphics.FromImage(bmpT))
                {
                    g.CompositingQuality = CompositingQuality.HighSpeed;
                    g.InterpolationMode = interpolationMode == 0 ? InterpolationMode.HighQualityBicubic : InterpolationMode.HighQualityBilinear;
                    g.CompositingMode = CompositingMode.SourceCopy;
                    g.Clear(bg);
                    g.DrawImage(bmp, -xCrop, -yCrop, w, h);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        bmpT.Save(memoryStream, imgCodec, encoderParams);
                        OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(imgPath));
                        using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
                        {
                            memoryStream.WriteTo(diskCacheStream);
                        }
                        memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    }
                }

                bmp.Dispose();
                bmpT.Dispose();
            }
        }
        catch (Exception ex)
        {
            Font font = new Font("verdana", 12);
            Bitmap bmp = new Bitmap(ex.Message.Length * 10, 50);
            Graphics g = Graphics.FromImage(bmp);
            g.DrawString(ex.Message.Replace("'", ""), font, new SolidBrush(Color.White), new PointF(5.0F, 5.0F));
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
        }
    }
Beispiel #46
0
    // Saves the image to specific location, save location includes filename
    private static void saveImageToLocation(Image theImage, string saveLocation)
    {
        // Strip the file from the end of the dir
        string saveFolder = Path.GetDirectoryName(saveLocation);
        if (!Directory.Exists(saveFolder))
        {
            Directory.CreateDirectory(saveFolder);
        }

        ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

        // Create an Encoder object based on the GUID
        // for the Quality parameter category.
        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

        // Create an EncoderParameters object.
        // An EncoderParameters object has an array of EncoderParameter
        // objects. In this case, there is only one
        // EncoderParameter object in the array.
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 90L);
        myEncoderParameters.Param[0] = myEncoderParameter;

        // Save to disk
        theImage.Save(saveLocation, jgpEncoder, myEncoderParameters);
    }
Beispiel #47
0
    public void SaveImage(ImageEventArgs e)
    {
        ImageCodecInfo myImageCodecInfo;
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;

        myImageCodecInfo = GetEncoderInfo(EncoderType);
        myEncoder = Encoder.Quality;
        myEncoderParameters = new EncoderParameters(1);
        myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
        myEncoderParameters.Param[0] = myEncoderParameter;

        try
        {
            string finalFile = System.IO.Path.Combine(e.FullSaveLocation, e.FullFileName) + "." + e.Extension;

            e.CapturedImage.Save(finalFile,
                                myImageCodecInfo, myEncoderParameters);

            //  e.CapturedImage.Save(finalFile);
            // e.CapturedImage.Save("c:\\users\\affan\\desktop\\jjajja.jpeg");
            ShowToastForm(finalFile);
            //this.Invoke(new ShowToastFormInvoker(ShowToastForm), e.FullSaveLocation + ".jpg");
        }
        catch(ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            myEncoderParameters.Dispose();
            myEncoderParameter.Dispose();
        }
    }
Beispiel #48
0
        /// <summary>
        /// 图片post处理
        /// </summary>
        /// <param name="types"></param>
        /// <param name="max_length"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        private IEnumerable <string> Images_C(string types, string reportNumber, int max_length, params string[] filter)
        {
            string result = "";
            string names  = "";
            var    files  = this.Files.GetFiles(max_length, filter);

            foreach (var file in files)
            {
                //首先先将图片保存
                string path   = AppDomain.CurrentDomain.BaseDirectory;
                var    format = Path.GetExtension(file.FileName);
                names = DateTime.Now.ToString("yyyyMMddhhmmssfff") + format;
                var savePath = path + "/UploadFile/" + reportNumber + "/";
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                file.SaveAs(Path.Combine(savePath, names));

                if (format.ToUpper().Equals(".MP4"))
                {
                    result = names;
                }
                else
                {
                    System.IO.Stream     oStream = file.InputStream;
                    System.Drawing.Image img     = System.Drawing.Image.FromStream(oStream);
                    #region 图片剪裁
                    switch (types)
                    {
                    //生成一个小的缩略图(暂定100*100) logo  同时生成一个小一倍的缩略图 min
                    case "0":
                        //生成一个小的缩略图(暂定100*100) logo
                        string newimgname = "logo" + names;

                        decimal oWidth = img.Width;     //原图宽度
                        decimal oHeight = img.Height;   //原图高度
                        decimal dStandard = 150;
                        decimal dWidth = img.Width, dHight = img.Height;

                        //判断图片大小
                        //宽高比对、低于标准原图创建
                        if (dWidth <= dHight)
                        {
                            if (dWidth > dStandard)
                            {
                                dHight = Math.Round(dHight / (dWidth / dStandard));
                                dWidth = dStandard;
                            }
                        }
                        else
                        {
                            if (dHight > dStandard)
                            {
                                dWidth = Math.Round(dWidth / (dHight / dStandard));
                                dHight = dStandard;
                            }
                        }
                        Bitmap   tImage = new Bitmap(int.Parse(dWidth.ToString()), int.Parse(dHight.ToString()));
                        Graphics g      = Graphics.FromImage(tImage);

                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;    //设置高质量插值法
                        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量,低速度呈现平滑程度
                        g.Clear(Color.Transparent);                                               //清空画布并以透明背景色填充

                        g.DrawImage(img, new Rectangle(0, 0, int.Parse(dWidth.ToString()), int.Parse(dHight.ToString())), new Rectangle(0, 0, int.Parse(oWidth.ToString()), int.Parse(oHeight.ToString())), GraphicsUnit.Pixel);

                        //图片质量设置
                        EncoderParameter  p;
                        EncoderParameters ps;

                        ps = new EncoderParameters(1);

                        p           = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100));
                        ps.Param[0] = p;

                        ImageCodecInfo ii = GetCodecInfo("image/jpeg");

                        try
                        {
                            //以JPG格式保存图片
                            tImage.Save(path + "/UploadFile/" + reportNumber + "/" + newimgname, ii, ps);
                        }
                        catch
                        {
                            result = "";

                            break;
                        }
                        //生成小缩略图结束,生成一个小一倍的缩略图 min
                        newimgname = "min" + names;
                        //int i_s = 400 / oWidth;
                        //tWidth = oWidth *i_s;
                        //tHeight = oHeight * i_s;
                        dStandard = 400;
                        decimal dWidths = img.Width, dHights = img.Height;

                        //判断图片大小
                        //宽高比对、低于标准原图创建
                        if (dWidths <= dHights)
                        {
                            if (dWidths > dStandard)
                            {
                                dHights = Math.Round(dHights / (dWidths / dStandard));
                                dWidths = dStandard;
                            }
                        }
                        else
                        {
                            if (dHights > dStandard)
                            {
                                dWidths = Math.Round(dWidths / (dHights / dStandard));
                                dHights = dStandard;
                            }
                        }
                        tImage = new Bitmap(int.Parse(dWidths.ToString()), int.Parse(dHights.ToString()));
                        g      = Graphics.FromImage(tImage);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;    //设置高质量插值法
                        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量,低速度呈现平滑程度
                        g.Clear(Color.Transparent);                                               //清空画布并以透明背景色填充

                        g.DrawImage(img, new Rectangle(0, 0, int.Parse(dWidths.ToString()), int.Parse(dHights.ToString())), new Rectangle(0, 0, int.Parse(oWidth.ToString()), int.Parse(oHeight.ToString())), GraphicsUnit.Pixel);


                        // newimgname = "new" + newimgname;
                        try
                        {
                            //以JPG格式保存图片
                            tImage.Save(path + "/UploadFile/" + reportNumber + "/" + newimgname, ii, ps);
                        }
                        catch
                        {
                            result = "";
                            break;
                        }
                        result = names;
                        //完成,不存入数据库只存原图片,因为缩略图是以原图片加前缀命名的
                        break;
                    }
                    #endregion
                }
                yield return(result);
            }

            //存储图片所需的绝对路径
        }
Beispiel #49
0
        /// 无损压缩图片
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param>
        /// <returns></returns>
        public bool GetPicThumbnail(string sFile, string dFile, int dHeight, int flag)
        {
            Image       iSource = Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int         sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Height > dHeight)
            {
                sH = dHeight;
                sW = (tem_size.Width * dHeight / tem_size.Height);
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap   ob = new Bitmap(sW, sH);
            Graphics g  = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
Beispiel #50
0
 public EncoderParameters(int count)
 {
     Param = new EncoderParameter[count];
 }
Beispiel #51
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String      dosya_adi = Request.QueryString["dosya"];
        Bitmap      orjinal   = new Bitmap(Server.MapPath(dosya_adi));
        ImageFormat format    = orjinal.RawFormat;

        Int32 orjWidth  = orjinal.Width;
        Int32 orjHeight = orjinal.Height;

        if (orjHeight < orjWidth)
        {
            if (orjinal.Width <= 349)
            {
                Int32 thumbGenislik = orjinal.Width;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbYukseklik = (Int32)((float)thumbGenislik / orjinal.Width * orjinal.Height);
                Bitmap   thumbResim     = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
            else
            {
                Int32 thumbGenislik = 349;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbYukseklik = (Int32)((float)thumbGenislik / orjinal.Width * orjinal.Height);
                Bitmap   thumbResim     = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
        }

        if (orjWidth < orjHeight)
        {
            if (orjinal.Height <= 349)
            {
                Int32 thumbYukseklik = orjinal.Height;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbGenislik = (Int32)((float)thumbYukseklik / orjinal.Height * orjinal.Width);
                Bitmap   thumbResim    = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g             = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
            else
            {
                Int32 thumbYukseklik = 349;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbGenislik = (Int32)((float)thumbYukseklik / orjinal.Height * orjinal.Width);
                Bitmap   thumbResim    = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g             = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
        }

        if (orjHeight == orjWidth)
        {
            if (orjinal.Height <= 349)
            {
                Int32 thumbGenislik = orjinal.Height;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbYukseklik = (Int32)((float)thumbGenislik / orjinal.Width * orjinal.Height);
                Bitmap   thumbResim     = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
            else
            {
                Int32 thumbGenislik = 349;

                ImageCodecInfo cInfo;
                if (format.Equals(ImageFormat.Gif) || format.Equals(ImageFormat.Png))
                {
                    cInfo = GetEncoder(ImageFormat.Png);
                    Response.ContentType = "image/png";
                }
                else
                {
                    cInfo = GetEncoder(ImageFormat.Jpeg);
                    Response.ContentType = "image/jpeg";
                }

                Encoder           enc     = Encoder.Quality;
                EncoderParameters eParams = new EncoderParameters(1);
                EncoderParameter  eParam  = new EncoderParameter(enc, 85L);
                eParams.Param[0] = eParam;

                Int32    thumbYukseklik = (Int32)((float)thumbGenislik / orjinal.Width * orjinal.Height);
                Bitmap   thumbResim     = new Bitmap(thumbGenislik, thumbYukseklik);
                Graphics g = Graphics.FromImage(thumbResim);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(orjinal, 0, 0, thumbGenislik, thumbYukseklik);

                Response.Clear();
                thumbResim.Save(Response.OutputStream, cInfo, eParams);
                thumbResim.Dispose();
            }
        }

        orjinal.Dispose();
    }
Beispiel #52
0
    ///<summary>
    ///cmResize Ảnh theo chiều rộng được đưa ra
    ///cm thank to: http://webxaula.com/website/Thay-doi-kich-thuoc-anh-khi-upload-41-1.html
    ///</summary>
    public void ResizeImage(string ImageSavePath, string fileName, int MaxWidthSideSize, Stream Buffer)
    {
        int intNewWidth;
        int intNewHeight;
        System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);
        ImageCodecInfo myImageCodecInfo;
        myImageCodecInfo = GetEncoderInfo("image/jpeg");
        //
        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter;

        //Giá trị width và height nguyên thủy của ảnh;
        int intOldWidth = imgInput.Width;
        int intOldHeight = imgInput.Height;

        //Kiểm tra xem ảnh ngang hay dọc;
        int intMaxSide;
        /*if (intOldWidth >= intOldHeight)
        {
        intMaxSide = intOldWidth;
        }
        else
        {
        intMaxSide = intOldHeight;
        }*/
        //Để xác định xử lý ảnh theo width hay height thì bạn bỏ note phần trên;
        //Ở đây mình chỉ sử dụng theo width nên gán luôn intMaxSide= intOldWidth; ^^;
        intMaxSide = intOldWidth;
        if (intMaxSide > MaxWidthSideSize)
        {
            //Gán width và height mới.
            double dblCoef = MaxWidthSideSize / (double)intMaxSide;
            intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
            intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
        }
        else
        {
            //Nếu kích thước width/height (intMaxSide) cũ ảnh nhỏ hơn MaxWidthSideSize thì giữ nguyên //kích thước cũ;
            intNewWidth = intOldWidth;
            intNewHeight = intOldHeight;
        }

        //Tạo một ảnh bitmap mới;
        Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
        //Phần EncoderParameter cho phép bạn chỉnh chất lượng hình ảnh ở đây mình để chất lượng tốt //nhất là 100L;
        myEncoderParameter = new EncoderParameter(myEncoder, 100L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        //Lưu ảnh;
        bmpResized.Save(ImageSavePath + fileName, myImageCodecInfo, myEncoderParameters);

        //Giải phóng tài nguyên;
        //Buffer.Close();
        imgInput.Dispose();
        bmpResized.Dispose();
    }
Beispiel #53
0
        /// <summary>
        /// 自定义生成缩略图
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <param name="thumbPath">缩略图路径</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static void GenerateThumb_ME(string imagePath)
        {
            Image image = Image.FromFile(imagePath);

            string      extension   = imagePath.Substring(imagePath.LastIndexOf(".")).ToLower();
            ImageFormat imageFormat = null;

            switch (extension)
            {
            case ".jpg":
            case ".jpeg":
                imageFormat = ImageFormat.Jpeg;
                break;

            case ".bmp":
                imageFormat = ImageFormat.Bmp;
                break;

            case ".png":
                imageFormat = ImageFormat.Png;
                break;

            case ".gif":
                imageFormat = ImageFormat.Gif;
                break;

            default:
                imageFormat = ImageFormat.Jpeg;
                break;
            }

            string save_folder  = imagePath.Substring(0, imagePath.LastIndexOf('\\')) + "\\";                                                                    //保存的路径
            string save_name    = imagePath.Substring(imagePath.LastIndexOf('\\') + 1, imagePath.LastIndexOf('.') - imagePath.LastIndexOf('\\') - 1) + "_thumb"; //保存的文件名,不包含拓展名
            string save_io_path = save_folder + save_name + extension;                                                                                           //保存的最终路径

            int toWidth  = image.Width / 3;
            int toHeight = image.Height;

            int x  = 0;
            int y  = 0;
            int ow = image.Width;
            int oh = image.Height;

            //款为原来的 1/3
            toHeight = image.Height * toWidth / image.Width;

            //新建一个bmp
            Image bitmap = new Bitmap(toWidth, toHeight);

            //新建一个画板
            Graphics g = Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(image,
                        new Rectangle(0, 0, toWidth, toHeight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);
            g.Dispose();

            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = 60;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[i];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    bitmap.Save(save_io_path, jpegICIinfo, ep);
                }
                else
                {
                    bitmap.Save(save_io_path, imageFormat);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    private void saveJpeg(string path, Bitmap img, long quality)
    {
        // Encoder parameter for image quality
        EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

        // Jpeg image codec
        ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

        if (jpegCodec == null)
            return;

        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;

        img.Save(path, jpegCodec, encoderParams);
    }
Beispiel #55
0
        /// <summary>
        ///A imagem original tem 1024x640 e 539KB. Todas as imagens serão reduzidas para 800x500...
        ///A primeira compactação foi 1 (qualidade baixa) com 10% de qualidade: Imagem de saída tem 14KB.
        ///A segunda compactação foi 1 (qualidade baixa) com 40% de qualidade: Imagem de saída tem 34KB.
        ///A terceira compactação foi 1 (qualidade baixa) com 70% de qualidade: Imagem de saída tem 54KB.
        ///A quarta compactação foi 1 (qualidade baixa) com 100% de qualidade: Imagem de saída tem 299KB.
        ///A quinta compactação foi 2 (qualidade alta) com 10% de qualidade: Imagem de saída tem 15KB.
        ///A sexta compactação foi 2 (qualidade alta) com 40% de qualidade: Imagem de saída tem 36KB.
        ///A setima compactação foi 2 (qualidade alta) com 70% de qualidade: Imagem de saída tem 57KB.
        ///A oitava compactação foi 2 (qualidade alta) com 100% de qualidade: Imagem de saída tem 310KB.
        /// </summary>
        /// <param name="larguraMaxima">Largura da Imagem Nova</param>
        /// <param name="alturaMaxima">Altura da Imagem Nova</param>
        /// <param name="arquivoOriginal">Arquivo original que será transformado</param>
        /// <param name="qualidade">Qualidade - 1 (Baixa) / 2 (Alta)</param>
        /// <param name="nivelQualidade">Define a porcentagem de compactação que será aplicada sobre a imagem - 0 mais baixa até 100 mais alta</param>
        /// <param name="excluirArquivoOriginal">Se enviar True ele irá excluir o Arquivo Original (enviado por parametro) e irá excluir o -comp1 (primeira compactação)</param>
        /// <returns>Retorna o nome do arquivo final - que será o mesmo do arquivoFinal mas acrescido de '-comp2.jpg' ao invés de apenas .jpg. Retorna "ERRO" se ocorrer excessão</returns>
        public string gerarNovaImagem(int larguraMaxima, int alturaMaxima, string arquivoOriginal, int qualidade, int nivelQualidade, bool excluirArquivoOriginal)
        {
            string arquivoFinal1 = arquivoOriginal.Replace(".jpg", "-comp1.jpg");
            string arquivoFinal2 = arquivoOriginal.Replace(".jpg", "-comp2.jpg");

            try
            {
                try
                {
                    if (File.Exists(arquivoFinal1) == true)
                    {
                        File.Delete(arquivoFinal1);
                    }
                }
                catch
                {
                    if (File.Exists(arquivoFinal2) == true)
                    {
                        File.Delete(arquivoFinal2);
                    }
                }

                //Analise e Dados técnicos de conversão feitos por essa classe - Fernando 102014... Eu enviei uma imagem em 600x400.
                //As imagens aqui descritas foram salvas dentro do Namespace Grafico na Pasta Grafico dentro dessa DLL.

                //A imagem original tem 1024x640 e 539KB. Todas as imagens serão reduzidas para 800x500...
                //A primeira compactação foi 1 (qualidade baixa) com 10% de qualidade: Imagem de saída tem 14KB.
                //A segunda compactação foi 1 (qualidade baixa) com 40% de qualidade: Imagem de saída tem 34KB.
                //A terceira compactação foi 1 (qualidade baixa) com 70% de qualidade: Imagem de saída tem 54KB.
                //A quarta compactação foi 1 (qualidade baixa) com 100% de qualidade: Imagem de saída tem 299KB.
                //A quinta compactação foi 2 (qualidade alta) com 10% de qualidade: Imagem de saída tem 15KB.
                //A sexta compactação foi 2 (qualidade alta) com 40% de qualidade: Imagem de saída tem 36KB.
                //A setima compactação foi 2 (qualidade alta) com 70% de qualidade: Imagem de saída tem 57KB.
                //A oitava compactação foi 2 (qualidade alta) com 100% de qualidade: Imagem de saída tem 310KB.

                #region Altera a resolução da imagem
                Image imagemOriginal;
                Image imagemAlterada;

                Graphics    grafico;                    //Gráfico
                Size        dimensaoFinal = new Size(); //Dimensão
                ImageFormat formato;                    //Formato

                imagemOriginal       = Image.FromFile(arquivoOriginal);
                dimensaoFinal        = this.novoTamanho(imagemOriginal.Size, new Size(larguraMaxima, alturaMaxima));
                dimensaoFinal.Height = alturaMaxima; //precisei FORÇAR por que tava dando problema...
                dimensaoFinal.Width  = larguraMaxima;

                //Define o novo formato da imagem
                formato = imagemOriginal.RawFormat;

                //Cria a nova imagem
                if (dimensaoFinal.Width == 0)
                {
                    dimensaoFinal.Width = 150;
                }

                if (dimensaoFinal.Height == 0)
                {
                    dimensaoFinal.Height = 150;
                }
                imagemAlterada = new Bitmap(dimensaoFinal.Width, dimensaoFinal.Height);

                grafico = Graphics.FromImage(imagemAlterada);

                //Opções relativas à qualidade da nova imagem
                if (qualidade == 1)
                {
                    grafico.CompositingQuality = CompositingQuality.HighSpeed;
                    grafico.SmoothingMode      = SmoothingMode.HighSpeed;
                    grafico.InterpolationMode  = InterpolationMode.Low;
                }
                if (qualidade == 2)
                {
                    grafico.CompositingQuality = CompositingQuality.HighQuality;
                    grafico.SmoothingMode      = SmoothingMode.HighQuality;
                    grafico.InterpolationMode  = InterpolationMode.High;
                }

                //Desenha a imagem no objeto gráfico this.grafico
                grafico.DrawImage(imagemOriginal, new Rectangle(0, 0, dimensaoFinal.Width, dimensaoFinal.Height));

                imagemAlterada.Save(arquivoFinal1);

                //inicia a compactação da imagem
                Image            myImage      = Image.FromFile(arquivoFinal1);
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, nivelQualidade);
                // Jpeg image codec
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                Thread.Sleep(500);

                myImage.Save(arquivoFinal2, jpegCodec, encoderParams);


                //tenta excluir o arquivoFinal1 (que é da primeira compactação) e o arquivo final (original) que foi enviado
                if (excluirArquivoOriginal)
                {
                    arquivoFinal1 = null;
                    //arquivoFinal2 = null;
                    imagemOriginal = null;
                    imagemAlterada = null;
                    grafico        = null;

                    formato       = null;
                    myImage       = null;
                    qualityParam  = null;
                    jpegCodec     = null;
                    encoderParams = null;
                    try
                    {
                        File.Delete(arquivoFinal1);
                    }
                    catch
                    {
                    }
                    try
                    {
                        File.Delete(arquivoOriginal);
                    }
                    catch
                    {
                    }
                }


                return(arquivoFinal2);

                #endregion
            }
            catch
            {
                return("ERRO");
            }
            finally
            {
                arquivoFinal1 = "";
                arquivoFinal2 = "";
            }
        }
Beispiel #56
0
    public static void saveJpeg(string path, Bitmap img)
    {
        // Encoder parameter for image quality
        EncoderParameter qualityParam =
           new EncoderParameter(Encoder.Quality, 85L);

        // Jpeg image codec
        ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg");
        if (jpegCodec == null)
            return;

        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;

        img.Save(path, jpegCodec, encoderParams);
    }
Beispiel #57
0
        private Hashtable OnGetTexture(Hashtable keysvals)
        {
            Hashtable reply      = new Hashtable();
            int       statuscode = 200;

            string imgkey = (string)keysvals["key"];

            if (imgkey == null || imgkey.Equals(""))
            {
                imgkey = SeaWaterTextureID;
            }

            m_log.Info("[MI IMAGESERVICE] Request for image " + imgkey);

            byte[] data = GetTexture(imgkey);

            if (data.Length == 1)
            {
                reply["str_response_string"] = "Error";
                reply["int_response_code"]   = 401;
                reply["content_type"]        = "text/plain";
            }
            else
            {
                // What follows was bluntly copied from the WorldMap module

                MemoryStream imgstream  = new MemoryStream();
                Bitmap       imgTexture = new Bitmap(1, 1);
                ManagedImage managedImage;
                Image        image = (Image)imgTexture;

                try
                {
                    // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                    imgstream = new MemoryStream();

                    // Decode image to System.Drawing.Image
                    if (OpenJPEG.DecodeToImage(data, out managedImage, out image))
                    {
                        // Save to bitmap
                        imgTexture = new Bitmap(image, new Size(256, 256));

                        ImageCodecInfo myImageCodecInfo;

                        Encoder myEncoder;

                        EncoderParameter  myEncoderParameter;
                        EncoderParameters myEncoderParameters = new EncoderParameters();

                        myImageCodecInfo = GetEncoderInfo("image/jpeg");

                        myEncoder = Encoder.Quality;

                        myEncoderParameter           = new EncoderParameter(myEncoder, 95L);
                        myEncoderParameters.Param[0] = myEncoderParameter;

                        myEncoderParameter           = new EncoderParameter(myEncoder, 95L);
                        myEncoderParameters.Param[0] = myEncoderParameter;

                        // Save bitmap to stream
                        imgTexture.Save(imgstream, myImageCodecInfo, myEncoderParameters);

                        // Write the stream to a byte array for output
                        data = imgstream.ToArray();
                    }
                }
                catch (Exception)
                {
                    m_log.Warn("[MI IMAGESERVICE]: Unable to generate image " + imgkey);
                }
                finally
                {
                    // Reclaim memory, these are unmanaged resources
                    imgTexture.Dispose();
                    image.Dispose();
                    imgstream.Close();
                    imgstream.Dispose();
                }
            }
            string dataStr = Convert.ToBase64String(data);

            reply["str_response_string"] = dataStr;
            reply["int_response_code"]   = statuscode;
            reply["content_type"]        = "image/jpeg";

            return(reply);
        }
Beispiel #58
0
        // Frame processing loop
        void frameLoop(int width, int height)
        {
            Stopwatch      fpsTimer;
            Stopwatch      fpsCountTimer;
            float          mspf      = 1000 / fps;
            int            frames    = 0;
            ImageCodecInfo jpegCodec = GetEncoder(ImageFormat.Jpeg);

            fpsCountTimer = Stopwatch.StartNew();

            while (true)
            {
                if (rawTextureData != null)
                {
                    fpsTimer = Stopwatch.StartNew();

                    byte[] _rawTextureData = rawTextureData;
                    byte[] bitmapRender    = new byte[_rawTextureData.Length];

                    // Rearrange _rawTextureData from bottom-up big-endian to top-down small-endian
                    Parallel.For(0, height, row =>
                    {
                        for (int col = 0; col < width; col++)
                        {
                            for (int i = 0; i < 4; i++)
                            {
                                bitmapRender[row * 4 * width + 4 * col + i] = _rawTextureData[(height - 1 - row) * 4 * width + 4 * col + (3 - i)];
                            }
                        }
                    });

                    // Load bitmap from byte bitmapRender
                    Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                    var    data   = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                    System.Runtime.InteropServices.Marshal.Copy(bitmapRender, 0, data.Scan0, bitmapRender.Length);
                    bitmap.UnlockBits(data);

                    // jpeg compression quality - realtime change
                    EncoderParameters jpegParams = new EncoderParameters(1);
                    EncoderParameter  jpegParam  = new EncoderParameter(Encoder.Quality, quality);
                    jpegParams.Param[0] = jpegParam;

                    using (MemoryStream finalFrameRender = new MemoryStream())
                    {
                        bitmap.Save(finalFrameRender, jpegCodec, jpegParams);

                        // Send frame for websocket delivery
                        websocket.SendFrame(serviceName, finalFrameRender.ToArray());

                        // FPS counter
                        frames++;
                    }

                    // Average FPS
                    avgFPS = frames / (fpsCountTimer.ElapsedMilliseconds / 1000f);

                    // Timestep - wait to meet our FPS target
                    if (fpsTimer.ElapsedMilliseconds < mspf)
                    {
                        Thread.Sleep((int)(mspf - fpsTimer.ElapsedMilliseconds));
                    }
                }
            }
        }
Beispiel #59
0
    /// <summary>
    /// 添加文字水印
    /// </summary>
    /// <param name="oldFilePath">原始图片路径</param>
    /// <param name="newFilePath">将要添加水印图片路径</param>
    /// <param name="waterPosition">水印位置</param>
    /// <param name="waterText">水印内容</param>
    public static void CreateWaterText(string oldFilePath, string newFilePath, int waterPosition, string waterText, int quality, string fontname, int fontsize)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(oldFilePath);
        Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);

        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);

        g.DrawImage(image, 0, 0, image.Width, image.Height);

        int _width = bmp.Width;
        int _height = bmp.Height;

        Font crFont = new Font(fontname, fontsize, FontStyle.Bold, GraphicsUnit.Pixel);
        SizeF crSize =g.MeasureString(waterText, crFont);

        float xpos = 0;
        float ypos = 0;
        switch (waterPosition)
        {
            case 3:
                xpos = ((float)_width * (float).99) - (crSize.Width / 2);
                ypos = (float)_height * (float).01;
                break;
            case 2:
                xpos = ((float)_width * (float).01) + (crSize.Width / 2);
                ypos = ((float)_height * (float).99) - crSize.Height;
                break;
            case 5:
                xpos = ((_width - crSize.Width) / 2) + crSize.Width / 2;    //奇怪的表达式
                ypos = (_height - crSize.Height) / 2 + crSize.Height / 2;
                break;
            case 1:

                xpos = ((float)_width * (float).01) + (crSize.Width / 2);
                ypos = (float)_height * (float).01;
                break;

            case 4:
            default:
                xpos = ((float)_width * (float).99) - (crSize.Width / 2);
                ypos = ((float)_height * (float).99) - crSize.Height;
                break;
        }

        StringFormat StrFormat = new StringFormat();
        StrFormat.Alignment = StringAlignment.Center;

        //可设置透明度
        SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(255, 255, 255, 255));
        g.DrawString(waterText, crFont, semiTransBrush, xpos, ypos, StrFormat);

        try
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];

            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                bmp.Save(newFilePath, ici, encoderParams);
            }
            else
            {
                bmp.Save(newFilePath);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            semiTransBrush.Dispose();
            image.Dispose();
            bmp.Dispose();
        }
    }