public static ImageHandler FromBitmapAsGreyscale(Bitmap bmp, string title = null)
        {
            if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb && bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb && bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppRgb)
            {
                throw new InvalidOperationException($"Неподдерживаемый формат изображения [{bmp.PixelFormat}]. Поддерживаются только форматы {nameof(System.Drawing.Imaging.PixelFormat.Format24bppRgb)},{nameof(System.Drawing.Imaging.PixelFormat.Format32bppRgb)} и {nameof(System.Drawing.Imaging.PixelFormat.Format32bppArgb)}.");
            }

            var imageHandler = new ImageHandler
            {
                Data        = ImageUtils.BitmapAsGreyscaleToByteArray(bmp, out float min, out float max),
                PixelFormat = ImagePixelFormat.Float,
                Format      = ImageFormat.Greyscale,
                Width       = bmp.Width,
                Height      = bmp.Height
            };

            Singleton.Get <ImageHandlerRepository>().Add(imageHandler);

            if (title == null)
            {
                title = "Bitmap " + Singleton.Get <ImageHandlerRepository>().GetAll().Count;
            }

            imageHandler._tags.Add(ImageHandlerTagKeys.MaximumValueF, max);
            imageHandler._tags.Add(ImageHandlerTagKeys.MinimumValueF, min);
            imageHandler._tags.Add(ImageHandlerTagKeys.Title, title);
            imageHandler._tags.Add(ImageHandlerTagKeys.Thumbnail, ThumbnailGenerator.Generate(bmp));
            imageHandler.Update();

            return(imageHandler);
        }
        public ActionResult Create(HttpPostedFileBase fileBase, string tags, string name)
        {
            var ownerId = User.Identity.GetUserId();

            if (ModelState.IsValid)
            {
                // Handle multiple files
                foreach (string key in Request.Files)
                {
                    if (Request.Files[key]?.ContentLength == 0)
                    {
                        continue;
                    }

                    // Get file object
                    var f = Request.Files[key] as HttpPostedFileBase;

                    // Save image locally with hash as the filename
                    string hash;
                    using (var sha1 = new SHA1CryptoServiceProvider())
                    {
                        hash = Convert.ToBase64String(sha1.ComputeHash(f.InputStream));
                    }

                    hash = hash.SafeString();

                    var filename = Server.MapPath(@"~\UserData\");

                    // Save to UserData folder
                    Directory.CreateDirectory(filename);
                    f.SaveAs(filename + hash);

                    // Create a new Picture from the file
                    var picture = new Picture
                    {
                        OwnerID       = ownerId,
                        Name          = name,
                        Hash          = hash,
                        Filesize      = f.ContentLength,
                        OriginalType  = f.ContentType,
                        ThumbnailData = ThumbnailGenerator.Generate(f.InputStream),
                        Tags          = ResolveTags(tags)
                    };

                    // Add the picture
                    _pictureRepo.Create(picture);
                }

                return(RedirectToAction("Index"));
            }

            return(View());
        }
Ejemplo n.º 3
0
    public void Render(int configuredDatasourceId, int?subTypeId, string title, DateRangeSelector dateSelector)
    {
        ThumbnailGenerator gen;
        Database           db;
        string             url;
        string             datasourceList;
        DateTime           start, end;

        DateRangeSelector.DateRanges dateRange;
        UrlBuilder clickUrl;

        db = Global.GetDbConnection();

        dateSelector.GetTimeRange(out start, out end, out dateRange);

        gen = new ThumbnailGenerator(db);

        //bytes = gen.Generate(configuredDatasourceId, subTypeId, start, end);
        //url = Common_SessionImage.StoreImageForDisplay(bytes, ViewState);

        url = gen.Generate(configuredDatasourceId, subTypeId, start, end);

        imgThumb.Src  = url;
        imgThumb.Alt  = title;
        chkTitle.Text = title;

        datasourceList = configuredDatasourceId.ToString();
        if (subTypeId != null)
        {
            datasourceList += "." + subTypeId;
        }

        clickUrl         = new UrlBuilder();
        clickUrl.URLBase = ResolveUrl("~/Members/Interactive-Report/");
        clickUrl.Parameters.AddParameter(QueryParameters.QUERY_DATASOURCE_LIST, datasourceList);

        //Store the ID information in an attribute
        DatasourceIdString = datasourceList;

        if (dateRange == DateRangeSelector.DateRanges.Custom)
        {
            clickUrl.Parameters.AddParameter(QueryParameters.QUERY_START, start);
            clickUrl.Parameters.AddParameter(QueryParameters.QUERY_END, end);
        }
        else
        {
            clickUrl.Parameters.AddParameter(QueryParameters.QUERY_TIME_RANGE, ((int)dateRange).ToString());
        }

        lnkDrillDown.HRef = clickUrl.ToString();
    }
        public void UpdateFromBitmap(Bitmap bmp)
        {
            if (Format != ImageFormat.Greyscale && PixelFormat != ImagePixelFormat.Byte)
            {
                throw new InvalidOperationException($"{nameof(ImageHandler)} имеет недопустимый формат пикселей: {PixelFormat}");
            }

            if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb && bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                throw new InvalidOperationException($"Неподдерживаемый формат изображения [{bmp.PixelFormat}]. Поддерживаются только форматы {nameof(System.Drawing.Imaging.PixelFormat.Format24bppRgb)} и {nameof(System.Drawing.Imaging.PixelFormat.Format32bppArgb)}.");
            }

            if (Format == ImageFormat.Greyscale)
            {
                Data = ImageUtils.BitmapAsGreyscaleToByteArray(bmp, out _, out _);
            }
            else
            {
                Data = ImageUtils.BitmapToByteArray(bmp);

                Format = bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb
                    ? ImageFormat.RGB
                    : ImageFormat.RGBA;
            }

            Width  = bmp.Width;
            Height = bmp.Height;

            _tags.SetOrAdd(ImageHandlerTagKeys.Thumbnail, ThumbnailGenerator.Generate(bmp));

            if (OpenGlTextureId.HasValue)
            {
                UploadToComputingDevice(true);
            }

            Update();
        }
Ejemplo n.º 5
0
        public async Task <SaveMediaResponse> SaveMedia(string name, string mimeType, Stream stream)
        {
            var path = ResolvePath(name);

            using (var fs = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                await stream.CopyToAsync(fs);
            }

            //  Generate thumbnail
            if (EnableThumbnailGeneration)
            {
                //  Generate thumbnail
                ThumbnailGenerator.Generate(path, mimeType);
            }

            return(new SaveMediaResponse()
            {
                Name = name,
                Path = path,
                Size = stream.Length,
                GenerateThumbnail = EnableThumbnailGeneration
            });
        }
Ejemplo n.º 6
0
        public static void CheckUploadedImageAndCreateThumbs(ImageUploadEditorAttribute attr, ref string temporaryFile)
        {
            ImageCheckResult[] supportedFormats = null;

            if (!attr.AllowNonImage)
            {
                supportedFormats = new ImageCheckResult[] {
                    ImageCheckResult.JPEGImage,
                    ImageCheckResult.GIFImage,
                    ImageCheckResult.PNGImage
                }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = attr.MinWidth;
            checker.MaxWidth    = attr.MaxWidth;
            checker.MinHeight   = attr.MinHeight;
            checker.MaxHeight   = attr.MaxHeight;
            checker.MaxDataSize = attr.MaxSize;

            Image image = null;

            try
            {
                var temporaryPath = UploadHelper.DbFilePath(temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (attr.MinSize != 0 && fs.Length < attr.MinSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooSmall,
                                                                UploadHelper.FileSizeDisplay(attr.MinSize)));
                    }

                    if (attr.MaxSize != 0 && fs.Length > attr.MaxSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooBig,
                                                                UploadHelper.FileSizeDisplay(attr.MaxSize)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result == ImageCheckResult.InvalidImage &&
                        attr.AllowNonImage)
                    {
                        return;
                    }

                    if (result > ImageCheckResult.UnsupportedFormat ||
                        (supportedFormats != null && Array.IndexOf(supportedFormats, result) < 0))
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result >= ImageCheckResult.FlashMovie)
                    {
                        return;
                    }

                    string basePath = UploadHelper.TemporaryPath;
                    string baseFile = Path.GetFileNameWithoutExtension(Path.GetFileName(temporaryPath));

                    TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                    if ((attr.ScaleWidth > 0 || attr.ScaleHeight > 0) &&
                        ((attr.ScaleWidth > 0 && (attr.ScaleSmaller || checker.Width > attr.ScaleWidth)) ||
                         (attr.ScaleHeight > 0 && (attr.ScaleSmaller || checker.Height > attr.ScaleHeight))))
                    {
                        using (Image scaledImage = ThumbnailGenerator.Generate(
                                   image, attr.ScaleWidth, attr.ScaleHeight, attr.ScaleMode, Color.Empty))
                        {
                            temporaryFile = baseFile + ".jpg";
                            fs.Close();
                            scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            temporaryFile = "temporary/" + temporaryFile;
                        }
                    }

                    var thumbSizes = attr.ThumbSizes.TrimToNull();
                    if (thumbSizes == null)
                    {
                        return;
                    }

                    foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                    {
                        var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                        int w, h;
                        if (dims.Length != 2 ||
                            !Int32.TryParse(dims[0], out w) ||
                            !Int32.TryParse(dims[1], out h) ||
                            w < 0 ||
                            h < 0 ||
                            (w == 0 && h == 0))
                        {
                            throw new ArgumentOutOfRangeException("thumbSizes");
                        }

                        using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, attr.ThumbMode, Color.Empty))
                        {
                            string thumbFile = Path.Combine(basePath,
                                                            baseFile + "_t" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                            thumbImage.Save(thumbFile);
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
Ejemplo n.º 7
0
        public void CheckUploadedImageAndCreateThumbs(ref string temporaryFile,
                                                      params ImageCheckResult[] supportedFormats)
        {
            if (supportedFormats == null ||
                supportedFormats.Length == 0)
            {
                supportedFormats = new ImageCheckResult[] { ImageCheckResult.JPEGImage, ImageCheckResult.GIFImage, ImageCheckResult.PNGImage }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = this.MinWidth;
            checker.MaxWidth    = this.MaxWidth;
            checker.MinHeight   = this.MinHeight;
            checker.MaxHeight   = this.MaxHeight;
            checker.MaxDataSize = this.MaxBytes;

            Image image = null;

            try
            {
                var temporaryPath = Path.Combine(UploadHelper.TemporaryPath, temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (this.MinBytes != 0 && fs.Length < this.MinBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en az {0} boyutunda olmalı!",
                                                                UploadHelper.FileSizeDisplay(this.MinBytes)));
                    }

                    if (this.MaxBytes != 0 && fs.Length > this.MaxBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en çok {0} boyutunda olabilir!",
                                                                UploadHelper.FileSizeDisplay(this.MaxBytes)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result > ImageCheckResult.FlashMovie ||
                        Array.IndexOf(supportedFormats, result) < 0)
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result != ImageCheckResult.FlashMovie)
                    {
                        string basePath = UploadHelper.TemporaryPath;
                        string baseFile = Path.GetFileNameWithoutExtension(temporaryFile);

                        TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                        if ((this.ScaleWidth > 0 || this.ScaleHeight > 0) &&
                            ((this.ScaleWidth > 0 && (this.ScaleSmaller || checker.Width > this.ScaleWidth)) ||
                             (this.ScaleHeight > 0 && (this.ScaleSmaller || checker.Height > this.ScaleHeight))))
                        {
                            using (Image scaledImage = ThumbnailGenerator.Generate(
                                       image, this.ScaleWidth, this.ScaleHeight, this.ScaleMode, Color.Empty))
                            {
                                temporaryFile = baseFile + ".jpg";
                                fs.Close();
                                scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }

                        var thumbSizes = this.ThumbSizes.TrimToNull();
                        if (thumbSizes != null)
                        {
                            foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                            {
                                var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                                int w, h;
                                if (dims.Length != 2 ||
                                    !Int32.TryParse(dims[0], out w) ||
                                    !Int32.TryParse(dims[1], out h) ||
                                    w < 0 ||
                                    h < 0 ||
                                    (w == 0 && h == 0))
                                {
                                    throw new ArgumentOutOfRangeException("thumbSizes");
                                }

                                using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, this.ThumbMode, Color.Empty))
                                {
                                    string thumbFile = Path.Combine(basePath,
                                                                    baseFile + "t_" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                                    if (this.ThumbQuality != 0)
                                    {
                                        var p = new System.Drawing.Imaging.EncoderParameters(1);
                                        p.Param[0] = new EncoderParameter(Encoder.Quality, 80L);

                                        ImageCodecInfo   jpegCodec = null;
                                        ImageCodecInfo[] codecs    = ImageCodecInfo.GetImageEncoders();
                                        // Find the correct image codec
                                        for (int i = 0; i < codecs.Length; i++)
                                        {
                                            if (codecs[i].MimeType == "image/jpeg")
                                            {
                                                jpegCodec = codecs[i];
                                            }
                                        }
                                        thumbImage.Save(thumbFile, jpegCodec, p);
                                    }
                                    else
                                    {
                                        thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
 public void Update()
 {
     ImageUtils.PopulateMinMax(this);
     _tags[ImageHandlerTagKeys.Thumbnail] = ThumbnailGenerator.Generate(this);
     ImageUpdated?.Invoke(new ImageUpdatedEventData(false));
 }
        public async Task <IHttpActionResult> TemporaryLargeFileUpload()
        {
            var token = Request.Headers.Contains("X-File-Token") ? Request.Headers.GetValues("X-File-Token").FirstOrDefault() : null;

            if (string.IsNullOrWhiteSpace(token))
            {
                return(InternalServerError(new Exception("File Token not provided.")));
            }


            try
            {
                var uploadFileService = new UploadFileService();
                UploadProcessingResult uploadResult = await uploadFileService.HandleRequest(Request);

                if (uploadResult.IsComplete)
                {
                    var baseFileName = Guid.NewGuid().ToString("N");
                    var saveFileName = $"{baseFileName}{Path.GetExtension(uploadResult.FileName)}";
                    var saveFilePath = Path.Combine(Path.GetDirectoryName(uploadResult.LocalFilePath), saveFileName);
                    if (File.Exists(saveFilePath))
                    {
                        File.Delete(saveFilePath);
                    }

                    File.Move(uploadResult.LocalFilePath, saveFilePath);

                    using (var sw = new StreamWriter(Path.ChangeExtension(saveFilePath, ".orig")))
                        sw.WriteLine(uploadResult.FileName);

                    //create thumb for image
                    var  isImage = false;
                    var  height  = 0;
                    var  width   = 0;
                    long size    = 0;
                    if (IsImageExtension(saveFileName))
                    {
                        isImage = true;

                        using (var fileContent = new FileStream(saveFilePath, FileMode.Open))
                        {
                            var imageChecker = new ImageChecker();
                            var checkResult  = imageChecker.CheckStream(fileContent, true, out var image);
                            height = imageChecker.Height;
                            width  = imageChecker.Width;
                            size   = imageChecker.DataSize;
                            if (checkResult != ImageCheckResult.JPEGImage &&
                                checkResult != ImageCheckResult.GIFImage &&
                                checkResult != ImageCheckResult.PNGImage)
                            {
                                throw new Exception(imageChecker.FormatErrorMessage(checkResult));
                            }
                            else
                            {
                                using (var thumbImage = ThumbnailGenerator.Generate(image, 128, 96, ImageScaleMode.CropSourceImage, Color.Empty))
                                {
                                    var thumbFile = Path.Combine(Path.GetDirectoryName(uploadResult.LocalFilePath), baseFileName + "_t.jpg");
                                    thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg);

                                    //height = thumbImage.Width;
                                    //width = thumbImage.Height;
                                }
                            }
                        }
                    }

                    return(Ok(new UploadResponse()
                    {
                        TemporaryFile = UrlCombine(UploadFileService.TempFolder, saveFileName),
                        IsImage = isImage,
                        Width = width,
                        Height = height,
                        Size = size
                    }));
                }

                return(Ok(HttpStatusCode.Continue));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }