コード例 #1
0
        protected string GenerateThumbnail(ThumbnailGenerator generator, string originalFilePath,
            string imagesBasePath, string thumbnailName)
        {
            string thumbnailPathNoExtension = Path.Combine(imagesBasePath, thumbnailName);

            string fullThumbnailPath = generator.GenerateThumbnail(originalFilePath, thumbnailPathNoExtension);

            return Path.GetFileName(fullThumbnailPath);
        }
コード例 #2
0
        /// <inheritdoc />
        public object Convert(object value, Type targetType, object format, CultureInfo culture)
        {
            if (value is string thumbnailFilename && !App.IsInDesignMode)
            {
                return(ThumbnailGenerator.GetThumbnail(
                           App.ViewModel.Playlist.ThumbsDirectory, thumbnailFilename));
            }

            return(default(ImageSource));
        }
コード例 #3
0
        static void Main()
        {
            ThumbnailGenerator thumbnail = new ThumbnailGenerator();

            thumbnail.ResizeAndKeepAspect();

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            Console.ReadLine();
        }
コード例 #4
0
        public void GetThumbnailSize_HigherHeight()
        {
            var size = ThumbnailGenerator.GetThumbnailSize(new Size(600, 800), new Size(200, 100));

            Assert.AreEqual(75, size.Width);
            Assert.AreEqual(100, size.Height);

            size = ThumbnailGenerator.GetThumbnailSize(new Size(600, 800), new Size(100, 200));
            Assert.AreEqual(100, size.Width);
            Assert.AreEqual(133, size.Height);
        }
コード例 #5
0
        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());
        }
コード例 #6
0
        /// <summary>
        /// Generates a thumbnail of the media item and stores to Media Thumbnail Cache folder
        /// </summary>
        public void GenerateThumbnail()
        {
            // we only care about storing generated thumnails, not default icons
            ThumbnailGenerator thumbnailGenerator = MediaManager.Config.GetThumbnailGenerator(mediaItem.Extension);

            if (!(thumbnailGenerator is ImageThumbnailGenerator))
            {
                return;
            }

            CreateThumbnail();
        }
コード例 #7
0
 private void UpdateRelease()
 {
     this.detailsEditor.CommitChanges(this.CollectionManager);
     foreach (TabItem tab in this.tabs.Items)
     {
         ImportTracksDiscEditor discEditor = (ImportTracksDiscEditor)tab.Content;
         discEditor.CommitChanges(this.CollectionManager);
     }
     ThumbnailGenerator.UpdateReleaseThumbnail(this.DatabaseRelease, this.imagesEditor);
     this.DatabaseRelease.DateAdded         = DateTime.Now;
     this.DatabaseRelease.DateModified      = DateTime.Now;
     this.DatabaseRelease.DateAudioModified = DateTime.Now;
 }
コード例 #8
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();
    }
コード例 #9
0
ファイル: DiskMediaStore.cs プロジェクト: Euler-KB/BusWork
        public Task DeleteMedia(string name)
        {
            string path = ResolvePath(name);

            FileHelpers.DeleteFile(new string[] { path });

            if (EnableThumbnailGeneration)
            {
                //  Delete thumbnail
                ThumbnailGenerator.Destroy(name);
            }

            return(Task.FromResult(0));
        }
コード例 #10
0
 public void GetFileInfo(string Path)
 {
     if (!File.Exists(Path) && !Directory.Exists(Path))
     {
         this.Name                = this.Language.ErrorMessages.MissingInvalid + ": " + Path;
         this.Description         = this.Language.ErrorMessages.MissingInvalid + ": " + Path;
         this.RepresentativeImage = ImageResources.MissingIcon;
     }
     else
     {
         try
         {
             SHFileInfo sHFileInfo = default(SHFileInfo);
             Shell32API.SHGetFileInfo(Path, 0u, ref sHFileInfo, (uint)Marshal.SizeOf(sHFileInfo), (ShellGetFileInfoFlags)1536);
             this.Name                = sHFileInfo.szDisplayName;
             this.Description         = sHFileInfo.szTypeName;
             this.RepresentativeImage = null;
             try
             {
                 if (Environment.OSVersion.Version.Major < 6)
                 {
                     this.RepresentativeImage = this.GetThumbnail(Path);
                 }
                 if (this.RepresentativeImage == null)
                 {
                     this.RepresentativeImage = ThumbnailGenerator.GenerateThumbnail(Path);
                 }
                 if (this.RepresentativeImage == null)
                 {
                     this.RepresentativeImage = ImageListThumbnailGenerator.GetJumboLargeThumbnail(Path);
                 }
                 if (this.RepresentativeImage == null)
                 {
                     this.RepresentativeImage = ImageResources.MissingIcon;
                 }
             }
             catch (Exception)
             {
                 this.RepresentativeImage = ImageResources.MissingIcon;
             }
         }
         catch (Exception)
         {
             this.Name                = this.Language.ErrorMessages.MissingInvalid + ": " + Path;
             this.Description         = this.Language.ErrorMessages.MissingInvalid + ": " + Path;
             this.RepresentativeImage = ImageResources.MissingIcon;
         }
     }
 }
コード例 #11
0
        /// <summary>
        /// The image compare.
        /// </summary>
        /// <param name="firstImagePath">The first image path.</param>
        /// <param name="secondImagePath">The second image path.</param>
        /// <returns>The <see cref="bool" />.</returns>
        private static bool ImageCompare(string firstImagePath, string secondImagePath)
        {
            simpleCompare = new BitmapCompare();
            double sim;

            using (var comImage = new Bitmap(firstImagePath))
                using (
                    var fileBitmap =
                        new Bitmap(
                            ThumbnailGenerator.GetThumbnailFromFile(secondImagePath, comImage.Width, comImage.Height, true, true)))
                {
                    sim = simpleCompare.GetSimilarity(comImage, fileBitmap);
                }

            return(Math.Round(sim, 3) > 0.75);
        }
コード例 #12
0
        public void New_Thumbnail_Generator_Custom_Configuration_TempFilePath_Should_Be_Set()
        {
            // Create the default ImageMagick configuration, which also initializes the underlying ImageMagick utility
            string temporaryImagesFilePath = @"f:\data\launchpad\images\temp";
            string policyMap = @"
                <policymap>
                   <policy domain=""resource"" name=""memory"" value=""3GiB""/> 
                   <policy domain=""resource"" name=""map"" value=""4GiB""/> 
                   <policy domain=""resource"" name=""time"" value=""unlimited""/> 
                </policymap>
            ";
            ImageMagickConfiguration config    = new ImageMagickConfiguration(policyMap, temporaryImagesFilePath);
            ThumbnailGenerator       generator = new ThumbnailGenerator(config);

            generator.Configuration.TemporaryImagesFilePath.Should().Contain("temp");
        }
コード例 #13
0
        public void New_Thumbnail_Generator_Custom_Configuration_TempFilePath_That_DoesNot_Exist_Should_Throw()
        {
            // Create the default ImageMagick configuration, which also initializes the underlying ImageMagick utility
            string             temporaryImagesFilePath = @"filepathdoesnotexist";
            string             policyMap = @"
                <policymap>
                   <policy domain=""resource"" name=""memory"" value=""3GiB""/> 
                   <policy domain=""resource"" name=""map"" value=""4GiB""/> 
                   <policy domain=""resource"" name=""time"" value=""unlimited""/> 
                </policymap>
            ";
            ThumbnailGenerator generator;
            Action             act = () => generator = new ThumbnailGenerator(new ImageMagickConfiguration(policyMap, temporaryImagesFilePath));

            act.Should().Throw <ArgumentException>();
        }
コード例 #14
0
        public Release ImportRelease(Stream stream)
        {
            using (XmlReader reader = this.CreateReader(stream))
            {
                reader.Read();
                Assert.IsTrue(reader.NodeType == XmlNodeType.XmlDeclaration);

                reader.Read();
                reader.AssertElementStart(Keys.Release);

                Release release = this.ReadRelease(reader);
                ThumbnailGenerator.UpdateReleaseThumbnail(release, this.collectionManager.ImageHandler);
                release.UpdateDynamicProperties();

                return(release);
            }
        }
コード例 #15
0
        public void New_Thumbnail_Generator_ConfigurationConstructor_Configuration_ShouldNot_Be_Null()
        {
            // Create the default ImageMagick configuration, which also initializes the underlying ImageMagick utility
            string temporaryImagesFilePath = @"f:\data\launchpad\images\temp";

            MagickNET.SetTempDirectory(temporaryImagesFilePath);
            string policyMap = @"
                <policymap>
                   <policy domain=""resource"" name=""memory"" value=""3GiB""/> 
                   <policy domain=""resource"" name=""map"" value=""4GiB""/> 
                   <policy domain=""resource"" name=""time"" value=""unlimited""/> 
                </policymap>
            ";
            ImageMagickConfiguration config    = new ImageMagickConfiguration(policyMap, temporaryImagesFilePath);
            ThumbnailGenerator       generator = new ThumbnailGenerator(config);

            generator.Configuration.Should().NotBeNull();
        }
コード例 #16
0
        protected override void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    thumbGen.Dispose();
                }

                thumbGen      = null;
                sbPathFixer   = null;
                paths         = null;
                symLinkHelper = null;
            }
            disposed = true;

            base.Dispose(disposing);
        }
コード例 #17
0
        private void HandleThumbnailIconViewButtonPressEvent(object sender, Gtk.ButtonPressEventArgs args)
        {
            int old_item = current_item;

            current_item = thumbnail_iconview.CellAtPosition((int)args.Event.X, (int)args.Event.Y, false);

            if (current_item < 0 || current_item >= items.Length)
            {
                current_item = old_item;
                return;
            }

            captions [old_item] = caption_textview.Buffer.Text;

            string caption = captions [current_item];

            if (caption == null)
            {
                captions [current_item] = caption = "";
            }
            caption_textview.Buffer.Text = caption;

            tag_treeview.Model = new TagStore(account.Facebook, tags [current_item], friends);

            IBrowsableItem item           = items [current_item];
            string         thumbnail_path = ThumbnailGenerator.ThumbnailPath(item.DefaultVersionUri);

            if (tag_image_eventbox.Children.Length > 0)
            {
                tag_image_eventbox.Remove(tag_image);
                tag_image.Destroy();
            }

            using (ImageFile image = new ImageFile(thumbnail_path)) {
                Gdk.Pixbuf data = image.Load();
                data             = PixbufUtils.ScaleToMaxSize(data, 400, 400);
                tag_image_height = data.Height;
                tag_image_width  = data.Width;
                tag_image        = new Gtk.Image(data);
                tag_image_eventbox.Add(tag_image);
                tag_image_eventbox.ShowAll();
            }
        }
コード例 #18
0
        private static bool InternalGenerateThumbnail(ImageViewModel target, DataOperationUnit dataOpUnit)
        {
            lock (target)
            {
                //暗号化している場合は無視する
                if (!Configuration.ApplicationConfiguration.LibraryIsEncrypted && !File.Exists(target.AbsoluteMasterPath))
                {
                    throw new FileNotFoundException(target.AbsoluteMasterPath);
                }

                var thumbnail = new ThumbnailViewModel();
                thumbnail.ID      = target.ID;
                thumbnail.ImageID = target.ID;

                var encryptImage = EncryptImageFacade.FindBy(target.ID);
                if (encryptImage != null)
                {
                    //暗号化実施時はサムネイル画像を出力しない
                    s_logger.Info($"Sunctum will not output a thumbnail image because it is in encrypted. {target.ID}");
                }
                else
                {
                    try
                    {
                        thumbnail.RelativeMasterPath = ThumbnailGenerator.SaveThumbnail(target.AbsoluteMasterPath, target.ID.ToString("N") + System.IO.Path.GetExtension(target.AbsoluteMasterPath));
                    }
                    catch (Exception e)
                    {
                        s_logger.Warn(e);
                        return(false);
                    }

                    s_logger.Debug($"Generate thumbnail ImageID={target.ID}");
                }

                Task.Factory.StartNew(() => RecordThumbnail(thumbnail));

                //Apply thumbnail
                target.Thumbnail = thumbnail;
                return(true);
            }
        }
コード例 #19
0
        private void UpdateImageForRelease(ReleaseData releaseData, ImageViewModel selectedItem)
        {
            string        extension = Path.GetExtension(selectedItem.DiscogsImage.Uri);
            string        mimeType  = MimeHelper.GetMimeTypeForExtension(extension);
            DatabaseImage image     = new DatabaseImage()
            {
                Description = "Auto import from Discogs",
                Extension   = extension,
                IsMain      = true,
                MimeType    = mimeType,
                Type        = ImageType.FrontCover
            };

            releaseData.Release.Images.Add(image);
            releaseData.Release.DateModified = DateTime.Now;
            this.CollectionManager.ImageHandler.StoreImage(image, selectedItem.Data);
            ThumbnailGenerator.UpdateReleaseThumbnail(releaseData.Release, this.CollectionManager.ImageHandler);
            this.CollectionManager.Save(releaseData.Release);

            this.CollectionManager.Operations.WriteTags(releaseData.Release);
        }
コード例 #20
0
ファイル: DiskMediaStore.cs プロジェクト: Euler-KB/BusWork
        public async Task <SaveMediaResponse> UpdateMedia(string originalName, string newName, string mimeType, Stream stream)
        {
            string path = ResolvePath(originalName);

            if (File.Exists(path))
            {
                //  Remove this file
                FileHelpers.DeleteFile(new string[] { path });

                //
                if (EnableThumbnailGeneration)
                {
                    ThumbnailGenerator.Destroy(originalName);
                }

                return(await SaveMedia(newName, mimeType, stream));
            }
            else
            {
                return(await SaveMedia(originalName, mimeType, stream));
            }
        }
コード例 #21
0
        // note:
        // do not allow to modify the constuctor parameters
        // (i.e. database, options)
        // through public properties later, since the scanner
        // may already use them after scanning has been started,
        // and some stuff has been initialized depending on the
        // options in the ctor already.
        public FilesystemVolumeScanner(Platform.Common.IO.DriveInfo drive,
                                       VolumeDatabase database,
                                       FilesystemScannerOptions options)
            : base(drive, database, options)
        {
            if (!drive.IsMounted)
            {
                throw new ArgumentException("Drive is not mounted", "drive");
            }

            if (Options.GenerateThumbnails && string.IsNullOrEmpty(Options.DbDataPath))
            {
                throw new ArgumentException("DbDataPath",
                                            "Thumbnail generation requires the DbDataPath option to be set");
            }

            disposed = false;
            //this.mimeInfo			  = new MimeInfo(false);
            this.sbPathFixer   = new StringBuilder(1024);
            this.paths         = new Paths(Options.DbDataPath, null, null);
            this.symLinkHelper = new SymLinkHelper(this);
            this.thumbGen      = new ThumbnailGenerator();
        }
コード例 #22
0
        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();
        }
コード例 #23
0
ファイル: DiskMediaStore.cs プロジェクト: Euler-KB/BusWork
        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
            });
        }
コード例 #24
0
        public void New_Thumbnail_Generator_DefaultConstructor_Configuration_ShouldNot_Be_Null()
        {
            ThumbnailGenerator generator = new ThumbnailGenerator();

            generator.Configuration.Should().NotBeNull();
        }
コード例 #25
0
ファイル: TweetThumbnail.cs プロジェクト: alphaKAI/OpenTween
 protected virtual List <ThumbnailInfo> GetThumbailInfo(PostClass post)
 {
     return(ThumbnailGenerator.GetThumbnails(post));
 }
コード例 #26
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();
                }
            }
        }
    }
コード例 #27
0
        private void StartServer()
        {
            Console.WriteLine("Starting DPAP server");

            DPAP.Database database = new DPAP.Database("DPAP");

            DPAP.Server server = new Server(System.Environment.UserName.ToString() + " f-spot photos");
            server.Port = 8770;
            server.AuthenticationMethod = AuthenticationMethod.None;
            int collision_count = 0;

            server.Collision += delegate {
                server.Name = System.Environment.UserName.ToString() + " f-spot photos" + "[" + ++collision_count + "]";
            };


            //FSpot.Photo photo = (FSpot.Photo) Core.Database.Photos.Get (1);

            try {
                Album a = new Album("test album");
                Tag   t = Core.Database.Tags.GetTagByName("Shared items");

                Tag []         tags   = { t };
                FSpot.Photo [] photos = Core.Database.Photos.Query(tags);
                int            i      = 0;

                foreach (FSpot.Photo photo in photos)
                {
                    string     thumbnail_path = ThumbnailGenerator.ThumbnailPath(photo.DefaultVersionUri);
                    FileInfo   f = new FileInfo(thumbnail_path);
                    DPAP.Photo p = new DPAP.Photo();

                    p.FileName  = photo.Name;
                    p.Thumbnail = thumbnail_path;
                    p.ThumbSize = (int)f.Length;
                    p.Path      = photo.DefaultVersionUri.ToString().Substring(7);
                    f           = new FileInfo(photo.DefaultVersionUri.ToString().Substring(7));
                    if (!f.Exists)
                    {
                        continue;
                    }

                    //if (++i > 2) break;
                    Console.WriteLine("Found photo " + p.Path + ", thumb " + thumbnail_path);
                    p.Title  = f.Name;
                    p.Size   = (int)f.Length;
                    p.Format = "JPEG";
                    database.AddPhoto(p);
                    a.AddPhoto(p);
                }

                database.AddAlbum(a);
                Console.WriteLine("Album count is now " + database.Albums.Count);
                server.AddDatabase(database);

                //server.GetServerInfoNode ();
                try {
                    server.Start();
                } catch (System.Net.Sockets.SocketException) {
                    Console.WriteLine("Server socket exception!");
                    server.Port = 0;
                    server.Start();
                }

                //DaapPlugin.ServerEnabledSchema.Set (true);

                //  if(!initial_db_committed) {
                server.Commit();

                //      initial_db_committed = true;
                //  }
            } catch (Exception e) {
                Console.WriteLine("Failed starting dpap server \n{0}", e);
            }
        }
コード例 #28
0
ファイル: TweetThumbnail.cs プロジェクト: tsubasa/OpenTween
 protected virtual Task <IEnumerable <ThumbnailInfo> > GetThumbailInfoAsync(PostClass post, CancellationToken token)
 => ThumbnailGenerator.GetThumbnailsAsync(post, token);
コード例 #29
0
 public static void MoveThumbnail(string old_path, string new_path)
 {
     File.Move(ThumbnailGenerator.ThumbnailPath(UriList.PathToFileUri(old_path)),
               ThumbnailGenerator.ThumbnailPath(UriList.PathToFileUri(new_path)));
 }
コード例 #30
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();
                }
            }
        }
    }
コード例 #31
0
 public void Update()
 {
     ImageUtils.PopulateMinMax(this);
     _tags[ImageHandlerTagKeys.Thumbnail] = ThumbnailGenerator.Generate(this);
     ImageUpdated?.Invoke(new ImageUpdatedEventData(false));
 }