示例#1
0
 /// <summary>
 /// Gets the compiled XSL stylesheet
 /// </summary>
 /// <param name="xslt">The string that presents the XSL stylesheet</param>
 /// <param name="enableDocumentFunctionAndInlineScript">true to enable document() function and inline script (like C#) of the XSL stylesheet</param>
 /// <param name="stylesheetResolver">Used to resolve any stylesheets referenced in XSLT import and include elements (if this is null, external resources are not resolved)</param>
 /// <returns></returns>
 public static XslCompiledTransform GetXslCompiledTransform(this string xslt, bool enableDocumentFunctionAndInlineScript = false, XmlResolver stylesheetResolver = null)
 {
     if (!string.IsNullOrWhiteSpace(xslt))
     {
         try
         {
             using (var stream = UtilityService.CreateMemoryStream(xslt.ToBytes()))
             {
                 using (var reader = XmlReader.Create(stream))
                 {
                     var xslTransform = new XslCompiledTransform(Utility.Logger.IsEnabled(LogLevel.Debug));
                     xslTransform.Load(reader, enableDocumentFunctionAndInlineScript ? new XsltSettings(true, true) : null, stylesheetResolver ?? new XmlUrlResolver());
                     return(xslTransform);
                 }
             }
         }
         catch (Exception ex)
         {
             if (ex.Message.IsContains("XSLT compile error"))
             {
                 throw new XslTemplateIsNotCompiledException(ex);
             }
             else
             {
                 throw new XslTemplateIsInvalidException(ex);
             }
         }
     }
     return(null);
 }
示例#2
0
 internal static ArraySegment <byte> Generate(string message, int width = 300, int height = 100, bool exportAsPng = false)
 {
     using (var bitmap = new Bitmap(width, height, PixelFormat.Format16bppRgb555))
     {
         using (var graphics = Graphics.FromImage(bitmap))
         {
             graphics.SmoothingMode = SmoothingMode.AntiAlias;
             graphics.Clear(Color.White);
             graphics.DrawString(message, new Font("Arial", 16, FontStyle.Bold), SystemBrushes.WindowText, new PointF(10, 40));
             using (var stream = UtilityService.CreateMemoryStream())
             {
                 bitmap.Save(stream, exportAsPng ? ImageFormat.Png : ImageFormat.Jpeg);
                 return(stream.ToArraySegment());
             }
         }
     }
 }
示例#3
0
        /// <summary>
        /// Creates a stream that contains Excel document from this data-set
        /// </summary>
        /// <param name="dataset">DataSet containing the data to be written to the Excel in OpenXML format</param>
        /// <returns>A stream that contains the Excel document</returns>
        /// <remarks>The stream that contains an Excel document in OpenXML format with MIME type is 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'</remarks>
        public static MemoryStream SaveAsExcel(this DataSet dataset)
        {
            // check dataset
            if (dataset == null || dataset.Tables == null || dataset.Tables.Count < 1)
            {
                throw new InformationNotFoundException("DataSet must be not null and contains at least one table");
            }

            // write dataset into stream
            var stream = UtilityService.CreateMemoryStream();

            using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
            {
                ExcelService.WriteExcelDocument(dataset, document);
            }
            return(stream);
        }
示例#4
0
 ArraySegment <byte> Generate(string value, int size, QRCodeGenerator.ECCLevel level)
 {
     using (var generator = new QRCodeGenerator())
         using (var data = generator.CreateQrCode(value, level))
             using (var code = new QRCode(data))
                 using (var bigBmp = code.GetGraphic(20))
                     using (var smallBmp = new Bitmap(size, size))
                         using (var graphics = Graphics.FromImage(smallBmp))
                         {
                             graphics.SmoothingMode     = SmoothingMode.HighQuality;
                             graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                             graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                             graphics.DrawImage(bigBmp, new Rectangle(0, 0, size, size));
                             using (var stream = UtilityService.CreateMemoryStream())
                             {
                                 smallBmp.Save(stream, ImageFormat.Png);
                                 return(stream.ToArraySegment());
                             }
                         }
 }
示例#5
0
        async Task ShowAsync(HttpContext context, CancellationToken cancellationToken)
        {
            // check "If-Modified-Since" request to reduce traffict
            var requestUri   = context.GetRequestUri();
            var useCache     = "true".IsEquals(UtilityService.GetAppSetting("Files:Cache:Thumbnails", "true")) && Global.Cache != null;
            var cacheKey     = $"{requestUri}".ToLower().GenerateUUID();
            var lastModified = useCache ? await Global.Cache.GetAsync <string>($"{cacheKey}:time", cancellationToken).ConfigureAwait(false) : null;

            var eTag          = $"thumbnail#{cacheKey}";
            var noneMatch     = context.GetHeaderParameter("If-None-Match");
            var modifiedSince = context.GetHeaderParameter("If-Modified-Since") ?? context.GetHeaderParameter("If-Unmodified-Since");

            if (eTag.IsEquals(noneMatch) && modifiedSince != null && lastModified != null && modifiedSince.FromHttpDateTime() >= lastModified.FromHttpDateTime())
            {
                context.SetResponseHeaders((int)HttpStatusCode.NotModified, eTag, lastModified.FromHttpDateTime().ToUnixTimestamp(), "public", context.GetCorrelationID());
                if (Global.IsDebugLogEnabled)
                {
                    await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Response to request with status code 304 to reduce traffic ({requestUri})").ConfigureAwait(false);
                }
                return;
            }

            // prepare
            var requestUrl  = $"{requestUri}";
            var queryString = requestUri.ParseQuery();

            var isNoThumbnailImage = requestUri.PathAndQuery.IsStartsWith("/thumbnail") && (requestUri.PathAndQuery.IsEndsWith("/no-image.png") || requestUri.PathAndQuery.IsEndsWith("/no-image.jpg"));
            var pathSegments       = requestUri.GetRequestPathSegments();

            var serviceName = pathSegments.Length > 1 && !pathSegments[1].IsValidUUID() ? pathSegments[1] : "";
            var systemID    = pathSegments.Length > 1 && pathSegments[1].IsValidUUID() ? pathSegments[1].ToLower() : "";
            var identifier  = pathSegments.Length > 5 && pathSegments[5].IsValidUUID() ? pathSegments[5].ToLower() : "";

            if (!isNoThumbnailImage && (string.IsNullOrWhiteSpace(identifier) || (string.IsNullOrWhiteSpace(serviceName) && string.IsNullOrWhiteSpace(systemID))))
            {
                throw new InvalidRequestException();
            }

            var handlerName = pathSegments[0];
            var format      = handlerName.IsEndsWith("pngs") || (isNoThumbnailImage && Handler.NoThumbnailImageFilePath.IsEndsWith(".png")) || context.GetQueryParameter("asPng") != null || context.GetQueryParameter("transparent") != null
                                ? "PNG"
                                : handlerName.IsEndsWith("webps")
                                        ? "WEBP"
                                        : "JPG";
            var isBig       = handlerName.IsStartsWith("thumbnaibig");
            var isThumbnail = isNoThumbnailImage || (pathSegments.Length > 2 && Int32.TryParse(pathSegments[2], out var isAttachment) && isAttachment == 0);

            if (!Int32.TryParse(pathSegments.Length > 3 ? pathSegments[3] : "", out var width))
            {
                width = 0;
            }
            if (!Int32.TryParse(pathSegments.Length > 4 ? pathSegments[4] : "", out var height))
            {
                height = 0;
            }
            var isCropped       = requestUrl.IsContains("--crop") || queryString.ContainsKey("crop");
            var croppedPosition = requestUrl.IsContains("--crop-top") || "top".IsEquals(context.GetQueryParameter("cropPos")) ? "top" : requestUrl.IsContains("--crop-bottom") || "bottom".IsEquals(context.GetQueryParameter("cropPos")) ? "bottom" : "auto";
            //var isUseAdditionalWatermark = queryString.ContainsKey("nw") ? false : requestUrl.IsContains("--btwm");

            var attachment = new AttachmentInfo
            {
                ID          = identifier,
                ServiceName = serviceName,
                SystemID    = systemID,
                IsThumbnail = isThumbnail,
                Filename    = isThumbnail
                                        ? identifier + (pathSegments.Length > 6 && Int32.TryParse(pathSegments[6], out var index) && index > 0 ? $"-{index}" : "") + ".jpg"
                                        : pathSegments.Length > 6 ? pathSegments[6].UrlDecode() : "",
                IsTemporary = false,
                IsTracked   = false
            };

            if ("webp".IsEquals(format) && pathSegments[2].Equals("1") && attachment.Filename.IsEndsWith(".webp"))
            {
                attachment.Filename = attachment.Filename.Left(attachment.Filename.Length - 5);
            }

            // check existed
            var isCached  = false;
            var hasCached = useCache && await Global.Cache.ExistsAsync(cacheKey, cancellationToken).ConfigureAwait(false);

            FileInfo fileInfo = null;

            if (!hasCached)
            {
                fileInfo = new FileInfo(isNoThumbnailImage ? Handler.NoThumbnailImageFilePath : attachment.GetFilePath());
                if (!fileInfo.Exists)
                {
                    context.ShowHttpError((int)HttpStatusCode.NotFound, "Not Found", "FileNotFoundException", context.GetCorrelationID());
                    return;
                }
            }

            // check permission
            async Task <bool> gotRightsAsync()
            {
                if (!isThumbnail)
                {
                    attachment = await context.GetAsync(attachment.ID, cancellationToken).ConfigureAwait(false);

                    return(await context.CanDownloadAsync(attachment, cancellationToken).ConfigureAwait(false));
                }
                return(true);
            }

            // generate
            async Task <byte[]> getAsync()
            {
                var thumbnail = useCache ? await Global.Cache.GetAsync <byte[]>(cacheKey, cancellationToken).ConfigureAwait(false) : null;

                if (thumbnail != null)
                {
                    isCached = true;
                    if (Global.IsDebugLogEnabled)
                    {
                        await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Cached thumbnail was found ({requestUri})").ConfigureAwait(false);
                    }
                }
                return(thumbnail);
            }

            async Task <byte[]> generateAsync()
            {
                byte[] thumbnail;

                // generate
                try
                {
                    using (var stream = UtilityService.CreateMemoryStream())
                    {
                        using (var image = this.Generate(fileInfo.FullName, width, height, isBig, isCropped, croppedPosition))
                        {
                            // add watermark

                            // get thumbnail image
                            image.Save(stream, "png".IsEquals(format) ? ImageFormat.Png : ImageFormat.Jpeg);
                        }
                        thumbnail = stream.ToBytes();
                    }
                }

                // read the whole file when got error
                catch (Exception ex)
                {
                    await context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Error occurred while generating thumbnail using Bitmap/Graphics => {ex.Message}", ex).ConfigureAwait(false);

                    thumbnail = await UtilityService.ReadBinaryFileAsync(fileInfo, cancellationToken).ConfigureAwait(false);
                }

                // update cache
                if (useCache)
                {
                    await Task.WhenAll
                    (
                        Global.Cache.AddSetMemberAsync($"{(attachment.SystemID.IsValidUUID() ? attachment.SystemID : attachment.ServiceName)}:Thumbnails", $"{attachment.ObjectID}:Thumbnails", cancellationToken),
                        Global.Cache.AddSetMemberAsync($"{attachment.ObjectID}:Thumbnails", cacheKey, cancellationToken),
                        Global.Cache.SetAsFragmentsAsync(cacheKey, thumbnail, 1440, cancellationToken),
                        Global.Cache.SetAsync($"{cacheKey}:time", fileInfo.LastWriteTime.ToHttpString(), 1440, cancellationToken),
                        Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Update a thumbnail image into cache successful [{requestUri} => {fileInfo.FullName}]") : Task.CompletedTask
                    ).ConfigureAwait(false);
                }

                return(thumbnail);
            }

            // prepare the thumbnail image
            var generateTask = hasCached ? getAsync() : generateAsync();

            if (!await gotRightsAsync().ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // flush the thumbnail image to output stream, update counter & logs
            var bytes = await generateTask.ConfigureAwait(false);

            lastModified = lastModified ?? fileInfo.LastWriteTime.ToHttpString();
            var lastModifiedTime = lastModified.FromHttpDateTime().ToUnixTimestamp();

            if ("webp".IsEquals(format))
            {
                if (isCached)
                {
                    using (var stream = UtilityService.CreateMemoryStream(bytes))
                    {
                        await context.WriteAsync(stream, "image/webp", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);
                    }
                }
                else
                {
                    using (var imageFactory = new ImageFactory())
                        using (var stream = UtilityService.CreateMemoryStream())
                        {
                            imageFactory.Load(bytes);
                            imageFactory.Quality = 100;
                            imageFactory.Save(stream);
                            await context.WriteAsync(stream, "image/webp", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);

                            if (useCache)
                            {
                                await Task.WhenAll
                                (
                                    Global.Cache.SetAsFragmentsAsync(cacheKey, stream.ToBytes(), cancellationToken),
                                    Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Re-update a thumbnail image with WebP image format into cache successful ({requestUri})") : Task.CompletedTask
                                ).ConfigureAwait(false);
                            }
                        }
                }
            }
            else
            {
                using (var stream = UtilityService.CreateMemoryStream(bytes))
                {
                    await context.WriteAsync(stream, $"image/{("png".IsEquals(format) ? "png" : "jpeg")}", null, eTag, lastModifiedTime, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);
                }
            }

            await Task.WhenAll
            (
                context.UpdateAsync(attachment, "Direct", cancellationToken),
                Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Thumbnails", $"Successfully show a thumbnail image ({requestUri})") : Task.CompletedTask
            ).ConfigureAwait(false);
        }

        Bitmap Generate(string filePath, int width, int height, bool asBig, bool isCropped, string cropPosition)
        {
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, TextFileReader.BufferSize))
            {
                using (var image = Image.FromStream(stream) as Bitmap)
                {
                    // clone original image
                    if ((width < 1 && height < 1) || (width.Equals(image.Width) && height.Equals(image.Height)))
                    {
                        return(image.Clone() as Bitmap);
                    }

                    // calculate size depend on width
                    if (height < 1)
                    {
                        height = image.Height * width / image.Width;
                        if (height < 1)
                        {
                            height = image.Height;
                        }
                    }

                    // calculate size depend on height
                    else if (width < 1)
                    {
                        width = image.Width * height / image.Height;
                        if (width < 1)
                        {
                            width = image.Width;
                        }
                    }

                    // generate thumbnail
                    return(isCropped
                                                ? this.Generate(image, width, height, asBig, cropPosition)
                                                : this.Generate(image, width, height, asBig));
                }
            }
        }

        Bitmap Generate(Bitmap image, int width, int height, bool asBig, string cropPosition)
        {
            using (var thumbnail = this.Generate(image, width, (image.Height * width) / image.Width, asBig))
            {
                // if height is less than thumbnail image's height, then return thumbnail image
                if (thumbnail.Height <= height)
                {
                    return(thumbnail.Clone() as Bitmap);
                }

                // crop image
                int top = cropPosition.IsEquals("auto")
                                        ? (thumbnail.Height - height) / 2
                                        : cropPosition.IsEquals("bottom")
                                                ? thumbnail.Height - height
                                                : 0;
                using (var cropped = new Bitmap(width, height))
                {
                    using (var graphics = Graphics.FromImage(cropped))
                    {
                        graphics.DrawImage(thumbnail, new Rectangle(0, 0, width, height), new Rectangle(0, top, width, height), GraphicsUnit.Pixel);
                    }
                    return(cropped.Clone() as Bitmap);
                }
            }
        }

        Bitmap Generate(Bitmap image, int width, int height, bool asBig)
        {
            // get and return normal thumbnail
            if (!asBig)
            {
                return(image.GetThumbnailImage(width, height, null, IntPtr.Zero) as Bitmap);
            }

            // get and return big thumbnail (set resolution of original thumbnail)
            else
            {
                using (var thumbnail = new Bitmap(width, height))
                {
                    using (var graphics = Graphics.FromImage(thumbnail))
                    {
                        graphics.SmoothingMode     = SmoothingMode.HighQuality;
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                        graphics.DrawImage(image, new Rectangle(0, 0, width, height));
                    }
                    return(thumbnail.Clone() as Bitmap);
                }
            }
        }
示例#6
0
        async Task FlushAsync(HttpContext context, CancellationToken cancellationToken)
        {
            // prepare
            var requestUri   = context.GetRequestUri();
            var pathSegments = requestUri.GetRequestPathSegments();

            var attachment = new AttachmentInfo
            {
                ID          = pathSegments.Length > 3 && pathSegments[3].IsValidUUID() ? pathSegments[3].ToLower() : "",
                ServiceName = pathSegments.Length > 1 && !pathSegments[1].IsValidUUID() ? pathSegments[1] : "",
                SystemID    = pathSegments.Length > 1 && pathSegments[1].IsValidUUID() ? pathSegments[1].ToLower() : "",
                ContentType = pathSegments.Length > 2 ? pathSegments[2].Replace("=", "/") : "",
                Filename    = pathSegments.Length > 4 && pathSegments[3].IsValidUUID() ? pathSegments[4].UrlDecode() : "",
                IsThumbnail = false
            };

            if (string.IsNullOrWhiteSpace(attachment.ID) || string.IsNullOrWhiteSpace(attachment.Filename))
            {
                throw new InvalidRequestException();
            }

            // check "If-Modified-Since" request to reduce traffict
            var eTag          = "file#" + attachment.ID;
            var noneMatch     = context.GetHeaderParameter("If-None-Match");
            var modifiedSince = context.GetHeaderParameter("If-Modified-Since") ?? context.GetHeaderParameter("If-Unmodified-Since");

            if (eTag.IsEquals(noneMatch) && modifiedSince != null)
            {
                context.SetResponseHeaders((int)HttpStatusCode.NotModified, eTag, modifiedSince.FromHttpDateTime().ToUnixTimestamp(), "public", context.GetCorrelationID());
                await context.FlushAsync(cancellationToken).ConfigureAwait(false);

                if (Global.IsDebugLogEnabled)
                {
                    context.WriteLogs(this.Logger, "Http.Downloads", $"Response to request with status code 304 to reduce traffic ({requestUri})");
                }
                return;
            }

            // get info & check permissions
            attachment = await context.GetAsync(attachment.ID, cancellationToken).ConfigureAwait(false);

            if (!await context.CanDownloadAsync(attachment, cancellationToken).ConfigureAwait(false))
            {
                throw new AccessDeniedException();
            }

            // check existed
            var cacheKey = attachment.ContentType.IsStartsWith("image/") && "true".IsEquals(UtilityService.GetAppSetting("Files:Cache:Images", "true")) && Global.Cache != null
                                ? $"Image#{attachment.Filename.ToLower().GenerateUUID()}"
                                : null;
            var hasCached = cacheKey != null && await Global.Cache.ExistsAsync(cacheKey, cancellationToken).ConfigureAwait(false);

            FileInfo fileInfo = null;

            if (!hasCached)
            {
                fileInfo = new FileInfo(attachment.GetFilePath());
                if (!fileInfo.Exists)
                {
                    if (Global.IsDebugLogEnabled)
                    {
                        context.WriteLogs(this.Logger, "Http.Downloads", $"Not found: {requestUri} => {fileInfo.FullName}");
                    }
                    context.ShowHttpError((int)HttpStatusCode.NotFound, "Not Found", "FileNotFoundException", context.GetCorrelationID());
                    return;
                }
            }

            // flush the file to output stream, update counter & logs
            if (hasCached)
            {
                var lastModified = await Global.Cache.GetAsync <long>($"{cacheKey}:time", cancellationToken).ConfigureAwait(false);

                var bytes = await Global.Cache.GetAsync <byte[]>(cacheKey, cancellationToken).ConfigureAwait(false);

                using (var stream = UtilityService.CreateMemoryStream(bytes))
                {
                    await context.WriteAsync(stream, attachment.ContentType, attachment.IsReadable()?null : attachment.Filename, eTag, lastModified, "public", TimeSpan.FromDays(366), null, context.GetCorrelationID(), cancellationToken).ConfigureAwait(false);
                }
                if (Global.IsDebugLogEnabled)
                {
                    context.WriteLogs(this.Logger, "Http.Downloads", $"Successfully flush a cached image ({requestUri})");
                }
            }
            else
            {
                await context.WriteAsync(fileInfo, attachment.IsReadable()?null : attachment.Filename, eTag, cancellationToken).ConfigureAwait(false);

                if (cacheKey != null)
                {
                    await Task.WhenAll
                    (
                        Global.Cache.SetAsFragmentsAsync(cacheKey, await UtilityService.ReadBinaryFileAsync(fileInfo, cancellationToken).ConfigureAwait(false), 1440, cancellationToken),
                        Global.Cache.SetAsync($"{cacheKey}:time", fileInfo.LastWriteTime.ToUnixTimestamp(), 1440, cancellationToken),
                        Global.IsDebugLogEnabled?context.WriteLogsAsync(this.Logger, "Http.Downloads", $"Update an image file into cache successful ({requestUri})") : Task.CompletedTask
                    ).ConfigureAwait(false);
                }
                if (Global.IsDebugLogEnabled)
                {
                    context.WriteLogs(this.Logger, "Http.Downloads", $"Successfully flush a file [{requestUri} => {fileInfo.FullName}]");
                }
            }

            await context.UpdateAsync(attachment, attachment.IsReadable()? "Direct" : "Download", cancellationToken).ConfigureAwait(false);
        }
示例#7
0
        ArraySegment <byte> Generate(string code, bool useSmallImage = true, List <string> noises = null)
        {
            // check code
            if (!code.Equals(""))
            {
                try
                {
                    code = code.Decrypt(CaptchaService.EncryptionKey, true).ToArray('-').Last();
                    var tempCode = "";
                    var space    = " ";
                    var spaceP   = "";
                    if (code.Length <= 5 && !useSmallImage)
                    {
                        spaceP = "  ";
                    }
                    else if (useSmallImage)
                    {
                        space = "";
                    }
                    for (int index = 0; index < code.Length; index++)
                    {
                        tempCode += spaceP + code[index].ToString() + space;
                    }
                    code = tempCode;
                }
                catch
                {
                    code = "I-n-valid";
                }
            }
            else
            {
                code = "Invalid";
            }

            // prepare sizae of security image
            var width  = 220;
            var height = 48;

            if (useSmallImage)
            {
                width  = 110;
                height = 24;
            }

            // create new graphic from the bitmap with random background color
            var backgroundColors = useSmallImage
                                ? new[] { Color.Orange, Color.Thistle, Color.LightSeaGreen, Color.Yellow, Color.YellowGreen, Color.NavajoWhite, Color.White }
                                : new[] { Color.Orange, Color.Thistle, Color.LightSeaGreen, Color.Violet, Color.Yellow, Color.YellowGreen, Color.NavajoWhite, Color.LightGray, Color.Tomato, Color.LightGreen, Color.White };

            var securityBitmap = this.CreateBackround(width, height, new[] { backgroundColors[UtilityService.GetRandomNumber(0, backgroundColors.Length)], backgroundColors[UtilityService.GetRandomNumber(0, backgroundColors.Length)], backgroundColors[UtilityService.GetRandomNumber(0, backgroundColors.Length)], backgroundColors[UtilityService.GetRandomNumber(0, backgroundColors.Length)] });
            var securityGraph  = Graphics.FromImage(securityBitmap);

            securityGraph.SmoothingMode = SmoothingMode.AntiAlias;

            // add noise texts (for big image)
            if (!useSmallImage)
            {
                // comuting noise texts for the image
                var texts = noises != null && noises.Count > 0
                                        ? noises
                                        : new List <string> {
                    "VIEApps", "vieapps.net", "VIEApps API Gateway", "VIEApps REST API"
                };

                var noiseTexts = new List <string> {
                    "Winners never quit", "Quitters never win", "Vietnam - The hidden charm", "Don't be evil", "Keep moving", "Connecting People", "Information at your fingertips", "No sacrifice no victory", "No paint no gain", "Enterprise Web Services", "On-Demand Services for Enterprise", "Cloud Computing Enterprise Services", "Where do you want to go today?", "Make business easier", "Simplify business process", "VIEApps", "vieapps.net"
                };
                noiseTexts.Append(texts);

                var noiseText = noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)];
                noiseText += " " + noiseText + " " + noiseText + " " + noiseText;

                // write noise texts
                securityGraph.DrawString(noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)] + " - " + noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)], new Font("Verdana", 10, FontStyle.Underline), new SolidBrush(Color.White), new PointF(0, 3));
                securityGraph.DrawString(noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)] + " - " + noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)], new Font("Verdana", 12, FontStyle.Bold), new SolidBrush(Color.White), new PointF(5, 7));
                securityGraph.DrawString(noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)] + " - " + noiseTexts[UtilityService.GetRandomNumber(0, noiseTexts.Count)], new Font("Arial", 11, FontStyle.Italic), new SolidBrush(Color.White), new PointF(-5, 20));
                securityGraph.DrawString(noiseText, new Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.White), new PointF(20, 28));
            }

            // add noise lines (for small image)
            else
            {
                // randrom index to make noise lines
                var randomIndex = UtilityService.GetRandomNumber(0, backgroundColors.Length);

                // first two lines
                var noisePen = new Pen(new SolidBrush(Color.Gray), 2);
                securityGraph.DrawLine(noisePen, new Point(width, randomIndex), new Point(randomIndex, height / 2 - randomIndex));
                securityGraph.DrawLine(noisePen, new Point(width / 3 - randomIndex, randomIndex), new Point(width / 2 + randomIndex, height - randomIndex));

                // second two lines
                noisePen = new Pen(new SolidBrush(Color.Yellow), 1);
                securityGraph.DrawLine(noisePen, new Point(((width / 4) * 3) - randomIndex, randomIndex), new Point(width / 3 + randomIndex, height - randomIndex));
                if (randomIndex % 2 == 1)
                {
                    securityGraph.DrawLine(noisePen, new Point(width - randomIndex * 2, randomIndex), new Point(randomIndex, height - randomIndex));
                }
                else
                {
                    securityGraph.DrawLine(noisePen, new Point(randomIndex, randomIndex), new Point(width - randomIndex * 2, height - randomIndex));
                }

                // third two lines
                randomIndex = UtilityService.GetRandomNumber(0, backgroundColors.Length);
                noisePen    = new Pen(new SolidBrush(Color.Magenta), 1);
                securityGraph.DrawLine(noisePen, new Point(((width / 6) * 3) - randomIndex, randomIndex), new Point(width / 5 + randomIndex, height - randomIndex + 3));
                if (randomIndex % 2 == 1)
                {
                    securityGraph.DrawLine(noisePen, new Point(width - randomIndex * 2, randomIndex - 1), new Point(randomIndex, height - randomIndex - 3));
                }
                else
                {
                    securityGraph.DrawLine(noisePen, new Point(randomIndex, randomIndex + 1), new Point(width - randomIndex * 2, height - randomIndex + 4));
                }

                // fourth two lines
                randomIndex = UtilityService.GetRandomNumber(0, backgroundColors.Length);
                noisePen    = new Pen(new SolidBrush(backgroundColors[UtilityService.GetRandomNumber(0, backgroundColors.Length)]), 1);
                securityGraph.DrawLine(noisePen, new Point(((width / 10) * 3) - randomIndex, randomIndex), new Point(width / 6 + randomIndex, height - randomIndex + 3));
                if (randomIndex % 2 == 1)
                {
                    securityGraph.DrawLine(noisePen, new Point(width - randomIndex * 3, randomIndex - 2), new Point(randomIndex, height - randomIndex - 2));
                }
                else
                {
                    securityGraph.DrawLine(noisePen, new Point(randomIndex, randomIndex + 2), new Point(width - randomIndex * 3, height - randomIndex + 2));
                }
            }

            // put the security code into the image with random font and brush
            var fonts  = new[] { "Verdana", "Arial", "Times New Roman", "Courier", "Courier New" };
            var brushs = new[]
            {
                new SolidBrush(Color.Black), new SolidBrush(Color.Blue), new SolidBrush(Color.DarkBlue), new SolidBrush(Color.DarkGreen),
                new SolidBrush(Color.Magenta), new SolidBrush(Color.Red), new SolidBrush(Color.DarkRed), new SolidBrush(Color.Black),
                new SolidBrush(Color.Firebrick), new SolidBrush(Color.DarkGreen), new SolidBrush(Color.Green), new SolidBrush(Color.DarkViolet)
            };

            if (useSmallImage)
            {
                var step = 0;
                for (var index = 0; index < code.Length; index++)
                {
                    float x = (index * 7) + step + UtilityService.GetRandomNumber(-1, 9);
                    float y = UtilityService.GetRandomNumber(-2, 0);

                    var writtenCode = code.Substring(index, 1);
                    if (writtenCode.Equals("I") || (UtilityService.GetRandomNumber() % 2 == 1 && !writtenCode.Equals("L")))
                    {
                        writtenCode = writtenCode.ToLower();
                    }

                    var addedX = UtilityService.GetRandomNumber(-3, 5);
                    securityGraph.DrawString(writtenCode, new Font(fonts[UtilityService.GetRandomNumber(0, fonts.Length)], UtilityService.GetRandomNumber(13, 19), FontStyle.Bold), brushs[UtilityService.GetRandomNumber(0, brushs.Length)], new PointF(x + addedX, y));
                    step += UtilityService.GetRandomNumber(13, 23);
                }
            }
            else
            {
                // write code
                var step = 0;
                for (int index = 0; index < code.Length; index++)
                {
                    var   font = fonts[UtilityService.GetRandomNumber(0, fonts.Length)];
                    float x = 2 + step, y = 10;
                    step += 9;
                    float fontSize = 15;
                    if (index > 1 && index < 4)
                    {
                        fontSize = 25;
                        x       -= 10;
                        y       -= 5;
                    }
                    else if (index > 3 && index < 6)
                    {
                        y        -= UtilityService.GetRandomNumber(3, 5);
                        fontSize += index;
                        step     += index / 5;
                        if (index == 4)
                        {
                            if (UtilityService.GetRandomNumber() % 2 == 1)
                            {
                                y += UtilityService.GetRandomNumber(8, 12);
                            }
                            else if (UtilityService.GetRandomNumber() % 2 == 2)
                            {
                                y        -= UtilityService.GetRandomNumber(2, 6);
                                fontSize += UtilityService.GetRandomNumber(1, 4);
                            }
                        }
                    }
                    else if (index > 5)
                    {
                        x        += UtilityService.GetRandomNumber(0, 4);
                        y        -= UtilityService.GetRandomNumber(0, 4);
                        fontSize += index - 7;
                        step     += index / 3 + 1;
                        if (index == 10)
                        {
                            if (UtilityService.GetRandomNumber() % 2 == 1)
                            {
                                y += UtilityService.GetRandomNumber(7, 14);
                            }
                            else if (UtilityService.GetRandomNumber() % 2 == 2)
                            {
                                y        -= UtilityService.GetRandomNumber(1, 3);
                                fontSize += UtilityService.GetRandomNumber(2, 5);
                            }
                        }
                    }
                    var writtenCode = code.Substring(index, 1);
                    if (writtenCode.Equals("I") || (UtilityService.GetRandomNumber() % 2 == 1 && !writtenCode.Equals("L")))
                    {
                        writtenCode = writtenCode.ToLower();
                    }
                    securityGraph.DrawString(writtenCode, new Font(font, fontSize, FontStyle.Bold), brushs[UtilityService.GetRandomNumber(0, brushs.Length)], new PointF(x + 2, y + 2));
                    securityGraph.DrawString(writtenCode, new Font(font, fontSize, FontStyle.Bold), brushs[UtilityService.GetRandomNumber(0, brushs.Length)], new PointF(x, y));
                }

                // fill it randomly with pixels
                int maxX = width, maxY = height, startX = 0, startY = 0;
                int random = UtilityService.GetRandomNumber(1, 100);
                if (random > 80)
                {
                    maxX -= maxX / 3;
                    maxY  = maxY / 2;
                }
                else if (random > 60)
                {
                    startX = maxX / 3;
                    startY = maxY / 2;
                }
                else if (random > 30)
                {
                    startX = maxX / 7;
                    startY = maxY / 4;
                    maxX  -= maxX / 5;
                    maxY  -= maxY / 8;
                }

                for (int iX = startX; iX < maxX; iX++)
                {
                    for (int iY = startY; iY < maxY; iY++)
                    {
                        if ((iX % 3 == 1) && (iY % 4 == 1))
                        {
                            securityBitmap.SetPixel(iX, iY, Color.DarkGray);
                        }
                    }
                }
            }

            // add random noise into image (use SIN)
            double divideTo   = 64.0d + UtilityService.GetRandomNumber(1, 10);
            int    distortion = UtilityService.GetRandomNumber(5, 11);

            if (useSmallImage)
            {
                distortion = UtilityService.GetRandomNumber(1, 5);
            }

            var noisedBitmap = new Bitmap(width, height, PixelFormat.Format16bppRgb555);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int newX = (int)(x + (distortion * Math.Sin(Math.PI * y / divideTo)));
                    if (newX < 0 || newX >= width)
                    {
                        newX = 0;
                    }

                    int newY = (int)(y + (distortion * Math.Cos(Math.PI * x / divideTo)));
                    if (newY < 0 || newY >= height)
                    {
                        newY = 0;
                    }

                    noisedBitmap.SetPixel(x, y, securityBitmap.GetPixel(newX, newY));
                }
            }

            // export as JPEG image
            using (var stream = UtilityService.CreateMemoryStream())
            {
                noisedBitmap.Save(stream, ImageFormat.Jpeg);
                securityGraph.Dispose();
                securityBitmap.Dispose();
                noisedBitmap.Dispose();
                return(stream.ToArraySegment());
            }
        }