예제 #1
0
 public ImageLinkImpl(User publisher, ImageFile file)
 {
     Publisher = publisher;
     File = file;
     _tags = new List<Tag>();
     DateCreate = DateTime.Now;
 }
예제 #2
0
        // this could be in the ScannerService, but then that service
        // takes a dependency on WPF, which I didn't want. Better to have
        // the dependencies wrapped into this service instead. Requires
        // FileIOPermission
        public BitmapSource ConvertScannedImage(ImageFile imageFile)
        {
            if (imageFile == null)
                return null;

            // save the image out to a temp file
            string fileName = System.IO.Path.GetTempFileName();

            // this is pretty hokey, but since SaveFile won't overwrite, we 
            // need to do something to both guarantee a unique name and
            // also allow SaveFile to write the file
            File.Delete(fileName);

            // now save using the same filename
            imageFile.SaveFile(fileName);

            BitmapFrame img;

            // load the file back in to a WPF type, this is just 
            // to get around size issues with large scans
            using (FileStream stream = File.OpenRead(fileName))
            {
                img = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                stream.Close();
            }

            // clean up
            File.Delete(fileName);

            return img;
        }
예제 #3
0
 public ImageLinkImpl(User publisher, ImageFile file, IEnumerable<Tag> tags)
     : this(publisher, file)
 {
     foreach (var tag in tags)
     {
         _tags.Add(tag);
     }
 }
예제 #4
0
파일: Model.cs 프로젝트: pchmielowski/Paint
 public PaintModel()
 {
     imageFile = new ImageFile(new Size(500, 500), Color.White);
       settings.BrushType = BrushType.SolidBrush;
       settings.DrawMode = DrawMode.Mixed;
       settings.PrimaryColor = Color.Chartreuse;
       settings.SecondaryColor = Color.BlueViolet;
 }
예제 #5
0
        private Dictionary<ImageFile, ImageLayouter> LayoutImage(PublishGroup publishGroup, MySortedList<ImageFile> bitmaps,bool isPOT,bool isSquare)
        {
            var result = new Dictionary<ImageFile, ImageLayouter>();
            uint order = 0;
            while (bitmaps.Count > 0)
            {
                var layouter = new ImageLayouter(PublishTarget.Current.DefaultImageSize, PublishTarget.Current.MaxImageSize, isPOT, isSquare);
                var copyList = new MySortedList<ImageFile>();
                copyList.AddRange(bitmaps);

                layouter.Generate(copyList);
                bitmaps.RemoveRange(layouter.UsedImages);

                if (layouter.ResultImageFixedSize != Size.Empty)
                {
                    FileInfo newFile = new FileInfo(publishGroup.GenerateNewFileName(PathManager.OutputImagesPath, order));
                    var resultImage = new ImageFile(newFile,true,true)
                        {
                            TextureRect = new Rectangle(Point.Empty, layouter.ResultImageFixedSize)
                        };

                    resultImage.Order = order;
                    if (PublishTarget.Current.IsPVR)
                    {
                        resultImage.IsPVREnabled = layouter.UsedImages.All(usedImage => usedImage.IsPVREnabled);
                    }
                    else
                    {
                        resultImage.IsPVREnabled = false;
                    }

                    result.Add(resultImage, layouter);
                    Logger.LogInfo("\t\tPack Image:{0}:\r\n", resultImage.FileInfo.Name);

                }
                else
                {
                    foreach (var usedImage in layouter.UsedImages)
                    {
                        Logger.LogInfo("\t\tToo Big Image:{0}:\r\n", usedImage);
                    }
                }
                ++order;
            }

            //foreach (var mergeResult in result)
            //{
            //    Logger.LogInfo("\t{0} {1}=>{2}:\r\n", mergeResult.Key, mergeResult.Value.ResultImageSize,
            //                   mergeResult.Value.ResultImageFixedSize);

            //    foreach (var imageFile in mergeResult.Value.UsedImages)
            //    {
            //        Logger.LogInfo("\t\t{0}:\r\n", imageFile);
            //    }
            //}

            return result;
        }
예제 #6
0
 public static uint AddFileAndTag(ImageFile file)
 {
     uint id = AddFile(file);
     if (id != uint.MaxValue)
     {
         AddFileTagItem(file, id);
     }
     return id;
 }
예제 #7
0
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            m_image = new ImageFile( (uint) imagePanel.Width, (uint) imagePanel.Height, ImageFile.PIXEL_FORMAT.RGBA8, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );

            UpdateGraph();

            Application.Idle += Application_Idle;
        }
예제 #8
0
        private void SaveImageToJPEGFile(ImageFile image, string fileName)
        {

            ImageProcess imgProcess = new ImageProcess();
            object convertFilter = "Convert";
            string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID;
            imgProcess.Filters.Add(convertFilterID, 0);
            SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatJPEG);
            image = imgProcess.Apply(image);
            image.SaveFile(fileName);
        }
예제 #9
0
        private static IEnumerable<Image> ExtractImages(ImageFile imageFile)
        {
            for (int frame = 1;frame<=imageFile.FrameCount;frame++)
            {
                imageFile.ActiveFrame = frame;
                ImageFile argbImage = imageFile.ARGBData.get_ImageFile(imageFile.Width,imageFile.Height);

                Image result = Image.FromStream(new MemoryStream((byte[])argbImage.FileData.get_BinaryData()));
                yield return result;
            }
        }
예제 #10
0
        private int LoadImages(int workflowID)
        {
            int rc = 0;
            if (!Directory.Exists(this.RootFolder))
                return rc;
            string[] dirlist = Directory.GetFiles(this.RootFolder,"*"+this.FileType);

            if (dirlist == null || dirlist.Length == 0)
                return rc;

            ImageFileList.Clear();
            foreach (string f in dirlist)
            {
                ImageFile imgf = new ImageFile();
                imgf.Filename=Path.GetFileNameWithoutExtension(f);
                imgf.Extension = Path.GetExtension(f);
                string[] nameitems = imgf.Filename.Split(new char[] { '_' });
                if (nameitems == null || nameitems.Length < 4)
                    continue;
                int n;
                if (int.TryParse(nameitems[(int)FileNameParse.WorkflowID], out n))
                {
                    imgf.WorkflowID = n;
                    if (imgf.WorkflowID != workflowID)
                        continue;
                }
                else
                    continue;
                if (int.TryParse(nameitems[(int)FileNameParse.TestID], out n))
                    imgf.TestID = n;
                else
                    continue;

                if (int.TryParse(nameitems[(int)FileNameParse.ImageID], out n))
                    imgf.ImageID = n;
                else
                    continue;

                if (nameitems.Length > (int)FileNameParse.ElementName)
                    imgf.ElementName = nameitems[(int)FileNameParse.ElementName];

                if (string.IsNullOrEmpty(imgf.ElementName))
                    continue;

                if (nameitems.Length > (int)FileNameParse.Comment)
                    imgf.Comment = nameitems[(int)FileNameParse.Comment];

                imgf.ImageData = Image.FromFile(f);
                if(imgf.ImageData!=null)
                    this.ImageFileList.Add(imgf);
            }
            return rc;
        }
 public void Verify_Add_Should_AddTheEntityToTheContext()
 {
     // Arrange
     Mock<IDbSet<ImageFile>> mockSetImageFiles;
     var mockContext = ImageFilesMockingSetup.DoMockingSetupForContext(false, out mockSetImageFiles);
     var repository = new ImageFilesRepository(mockContext.Object);
     var imageFiles = new ImageFile { Active = true, CustomKey = "SALVATORE-RAA", };
     // Act
     repository.Add(imageFiles);
     // Assert
     mockSetImageFiles.Verify(x => x.Add(imageFiles), Times.Once);
 }
예제 #12
0
        /// <inheritdoc/>
        public override MediaFile Clone()
        {
            ImageFile imageFileClone = new ImageFile(this.Configuration);
            imageFileClone.ImageType = this.ImageType;
            imageFileClone.Season = this.Season;
            imageFileClone.Description = this.Description;
            imageFileClone.URL = this.URL;
            imageFileClone.URLLocalFilesystem = this.URLLocalFilesystem;
            imageFileClone.Filename = this.Filename;
            imageFileClone.Extension = this.Extension;
            imageFileClone.Server = this.Server;
            imageFileClone.Media = this.Media;

            return (ImageFile)imageFileClone;
        }
예제 #13
0
        private ImageFile Process (CommonDialog commonDialog, Device scannerDevice, int DPI)
        {
            if (scannerDevice != null)
            {
                Item scannerItem = scannerDevice.Items[1];
                if (DPI == 200)
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 1700, 2338, 0, 0);
                else if (DPI == 300)
                    AdjustScannerSettings(scannerItem, DPI, 0, 0, 2550, 3507, 0, 0);

                object scanResult = commonDialog.ShowTransfer(scannerItem, WIA.FormatID.wiaFormatJPEG, false);
                if (scanResult != null)
                    image = (ImageFile)scanResult;
            }
            return image;
        }
예제 #14
0
	public static void Main (string [] args)
	{
		if (args.Length != 1) {
			Console.Out.WriteLine ("usage: mono StripImageData.exe [jpegfile]");
			return;
		}

		ImageFile file = new ImageFile (args [0]);

		file.Mode = File.AccessMode.Write;

		long greatest_segment_position = 0;
		long greatest_segment_length = 0;

		// collect data segments
		while (true) {

			long sos = file.Find (new byte [] {0xFF, 0xDA}, file.Tell);

			if (sos == -1)
				break;

			file.Seek (sos);

			long segment_length = SkipDataSegment (file);

			if (segment_length > greatest_segment_length) {
				greatest_segment_length = segment_length;
				greatest_segment_position = sos;
			}
		}

		if (greatest_segment_length == 0)
		{
			Console.Out.WriteLine ("doesn't look like an jpeg file");
			return;
		}

		System.Console.WriteLine ("Stripping data segment at {0}", greatest_segment_position);

		file.RemoveBlock (greatest_segment_position, greatest_segment_length);
		file.Seek (greatest_segment_position);
		file.WriteBlock (image_data);
		file.Mode = File.AccessMode.Closed;
	}
        private ActionResult HandleFound(IWinDbgBackend backend, string company, string login, string password, ImageFile imageFile)
        {
            backend.LogImageFileFound(imageFile);

            var routeData = new
                                {
                                    company,
                                    login,
                                    password,
                                    imageName = imageFile.Name,
                                    pdbHash = imageFile.SymbolHash,
                                    sourcePath = "XVAR2X",
                                    computerName = "XCNX",
                                    computerUser = "******",
                                };

            var url = Request.Url.GetLeftPart(UriPartial.Authority) + Url.RouteUrl("Source", routeData);
            return PdbFile(backend, imageFile, url);
        }
예제 #16
0
        public static void AddImageTagItem(ImageFile imageFile, uint fileId)
        {
            var orderItem = AddFileTagItem(imageFile, fileId);

            if (orderItem != null)
            {
                if (imageFile.TextureRect.HasValue)
                {
                    orderItem.TextureRect = new RectU
                    {
                        Origin = new PointU
                        {
                            X = (uint)imageFile.TextureRect.Value.X,
                            Y = (uint)imageFile.TextureRect.Value.Y
                        },
                        Size = new SizeU
                        {
                            Width = (uint)imageFile.TextureRect.Value.Width,
                            Height = (uint)imageFile.TextureRect.Value.Height
                        }
                    };
                }

                if (imageFile.Offset.HasValue)
                {
                    orderItem.Offset = new PointU
                    {
                        X = (uint)imageFile.Offset.Value.X,
                        Y = (uint)imageFile.Offset.Value.Y
                    };

                    if (!imageFile.OriginalSize.IsEmpty)
                    {
                        orderItem.OriginalSize = new SizeU
                        {
                            Width = (uint)imageFile.OriginalSize.Width,
                            Height = (uint)imageFile.OriginalSize.Height
                        };
                    }
                }
            }
        }
예제 #17
0
        // this will choke on large images (like 1200dpi scans)
        // for that reason, you may want to do the conversion by
        // saving the ImageFile to a temp file and then loading it
        // in to convert it, as we do in the revised method above
        public BitmapSource InMemoryConvertScannedImage(ImageFile imageFile)
        {
            if (imageFile == null)
                return null;

            Vector vector = imageFile.FileData;

            if (vector != null)
            {
                byte[] bytes = vector.get_BinaryData() as byte[];

                if (bytes != null)
                {
                    var ms = new MemoryStream(bytes);
                    return BitmapFrame.Create(ms);
                }
            }

            return null;
        }
예제 #18
0
        public void AddImageToProduct()
        {
            // Arrange
            var images = Client.GetImagesForProduct(productId).Result;
            var imageCount = images.Result == null ? 0 : images.Result.Count;

            // Act
            var filePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Images\\100001\\") + "01.jpg";
            var imageFile = new ImageFile
                                {
                                    file_content = File.ReadAllBytes(filePath),
                                    file_mime_type = "image/jpeg",
                                    file_name = "100001_01"
                                };
            var response = Client.AddImageToProduct(productId, imageFile).Result;

            // Assert
            Assert.IsFalse(response.HasErrors, response.ErrorString);
            Assert.Less(0, response.Result);
            var newImages = Client.GetImagesForProduct(productId).Result;
            Assert.AreEqual(imageCount + 1, newImages.Result.Count);
        }
예제 #19
0
        public static void AddImage(ImageFile imageFile, PublishTarget target,bool isPacked=true,bool isOptimzed=true,bool isPVREnabled=false,bool isPOT=false,bool isSquare=false)
        {
            if (!Images.ContainsKey(imageFile) && !ImageFilePathDict.ContainsKey(imageFile.FileInfo.FullName) && !ImageFileNameDict.ContainsKey(imageFile.FileInfo.Name))
            {
                Images.Add(imageFile, false);
                ImageFilePathDict.Add(imageFile.FileInfo.FullName,imageFile);
                ImageFileNameDict.Add(imageFile.FileInfo.Name, imageFile);
                imageFile.IsPacked = isPacked;
                imageFile.IsOptimzed = isOptimzed;
                imageFile.IsPVREnabled = isPVREnabled;
                imageFile.IsPOT = isPOT;
                imageFile.IsSquare = isSquare;
            }
            else
            {
                Logger.LogErrorLine("\tDuplicate File name: {0}\tVS\t{1}", imageFile,
                                    Images[imageFile]);
            }

            if (imageFile.PublishGroup != null && !imageFile.PublishGroup.PublishInfo.IsPublish(target))
            {
                //Logger.LogInfoLine("DON'T pack {0}", imageFile.FileInfo.Name);
                return;
            }

            if (!isPacked)
            {
                //Logger.LogInfoLine("DON'T pack {0}", imageFile.FileInfo.Name);
                return;
            }

            MySortedList<ImageFile> groupFiles;
            if (!ImageGroups.TryGetValue(imageFile.PublishGroup, out groupFiles))
            {
                groupFiles = new MySortedList<ImageFile>();
                ImageGroups.Add(imageFile.PublishGroup, groupFiles);
            }
            groupFiles.Add(imageFile);
        }
예제 #20
0
        /// <summary>
        /// Very wasteful method that computes the spectrum of a source image
        /// </summary>
        /// <param name="_source"></param>
        /// <returns></returns>
        ImageFile       ComputeSpectrum(ImageFile _source, float _scaleFactor)
        {
            uint size   = _source.Width;
            uint offset = size >> 1;
            uint mask   = size - 1;

            Complex[,]      signal = new Complex[size, size];
            _source.ReadPixels((uint _X, uint _Y, ref float4 _color) => {
                signal[_X, _Y].Set(_color.x, 0);
            });

            SharpMath.FFT.FFT2D_GPU FFT = new SharpMath.FFT.FFT2D_GPU(m_device, size);
            Complex[,]      spectrum = FFT.FFT_Forward(signal);
            FFT.Dispose();

            ImageFile result = new ImageFile(size, size, _source.PixelFormat, _source.ColorProfile);

            result.WritePixels((uint _X, uint _Y, ref float4 _color) => {
                float V = _scaleFactor * (float)spectrum[(_X + offset) & mask, (_Y + offset) & mask].r;
                _color.Set(V, V, V, 1.0f);
            });
            return(result);
        }
        private bool AskUserIfWantsToCorrectTheFile(ImageFile imageFile)
        {
            while (true)
            {
                Console.Write($"{imageFile.Path} - date: {imageFile.PossibleDate} - Correct the file to date: {GetDateTimeFromFileName(imageFile)}? (y/n): ");
                var answer = Console.ReadKey().KeyChar;
                Console.WriteLine();

                switch (answer)
                {
                case 'y':
                case 'Y':
                    return(true);

                case 'n':
                case 'N':
                    return(false);

                default:
                    continue;
                }
            }
        }
예제 #22
0
        public static void Test()
        {
            AbstractFile file1, file2, file3, file4, folder1, folder2, folder3;

            file1 = new ImageFile("图片1.gif");
            file2 = new ImageFile("图片2.png");
            file3 = new TextFile("文本1.txt");
            file4 = new TextFile("文本2.docx");

            folder1 = new Folder("图");
            folder1.add(file1);
            folder1.add(file2);

            folder2 = new Folder("文本");
            folder2.add(file3);
            folder2.add(file4);

            folder3 = new Folder("root");
            folder3.add(folder1);
            folder3.add(folder2);

            folder3.display();
        }
예제 #23
0
        protected void ScanPhotoDirectory(ImportController controller, SafeUri uri, PhotoList photo_list)
        {
            var enumerator = new RecursiveFileEnumerator(uri)
            {
                Recurse        = controller.RecurseSubdirectories,
                CatchErrors    = true,
                IgnoreSymlinks = true
            };

            foreach (var file in enumerator)
            {
                if (ImageFile.HasLoader(new SafeUri(file.Uri.ToString(), true)))
                {
                    var info = new FileImportInfo(new SafeUri(file.Uri.ToString(), true));
                    ThreadAssist.ProxyToMain(() =>
                                             photo_list.Add(info));
                }
                if (!run_photoscanner)
                {
                    return;
                }
            }
        }
예제 #24
0
        private void button1_Click(object sender, EventArgs e)
        {
            loadTex(0);
            OpenFileDialog open = new OpenFileDialog();

            open.Filter = "DDS Files|*.dds";
            open.Title  = "Please select the file to mod with";
            if (open.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            try
            {
                ImageFile im = KFreonLib.Textures.Creation.LoadAKImageFile(null, open.FileName);
                tex2D.OneImageToRuleThemAll(im, pathCooked, im.imgData);

                SaveChanges();
            }
            catch (Exception exc)
            {
                MessageBox.Show("An error occurred: \n" + exc);
            }
        }
예제 #25
0
 private void EnumerateImageFiles(string[] filePaths)
 {
     foreach (var filePath in filePaths)
     {
         var imageFile = new ImageFile();
         imageFile.Path        = filePath;
         imageFile.Type        = filePath.Contains("COLOR") ? ImageType.Color : (filePath.Contains("THERM") ? ImageType.Thermal : ImageType.Unknown);
         imageFile.Timestamp   = ParseTimestampInFileName(Path.GetFileName(filePath));
         imageFile.SizeInBytes = new FileInfo(filePath).Length;
         var key = String.Format("{0}-{1:00}-{2:00}", imageFile.Timestamp.Year, imageFile.Timestamp.Month, imageFile.Timestamp.Day);
         List <ImageFile> list = null;
         if (!_imagesByDateString.TryGetValue(key, out list))
         {
             list = new List <ImageFile>();
             _imagesByDateString[key] = list;
         }
         list.Add(imageFile);
         if (_pathsExamined++ % 1000 == 0)
         {
             UpdateImageFileStatsLabels();
         }
     }
 }
        private bool disposedValue = false; // To detect redundant calls

        private void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (TerminateOnDispose)
                {
                    try
                    {
                        Terminate(NtStatus.STATUS_WAIT_1);
                    }
                    catch (NtException)
                    {
                    }
                }

                Process?.Close();
                Thread?.Close();
                ImageFile?.Close();
                SectionHandle?.Close();
                IFEOKeyHandle?.Close();
                disposedValue = true;
            }
        }
        public void AddImageToProduct()
        {
            // Arrange
            var images     = _productImageFixture.Client.GetImagesForProduct(_productImageFixture.productId).Result;
            var imageCount = images.Result == null ? 0 : images.Result.Count;

            // Act
            var filePath  = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Images\\100001\\") + "01.jpg";
            var imageFile = new ImageFile
            {
                file_content   = File.ReadAllBytes(filePath),
                file_mime_type = "image/jpeg",
                file_name      = "100001_01"
            };
            var response = _productImageFixture.Client.AddImageToProduct(_productImageFixture.productId, imageFile).Result;

            // Assert
            Assert.False(response.HasErrors, response.ErrorString);
            Assert.True(0 < response.Result);
            var newImages = _productImageFixture.Client.GetImagesForProduct(_productImageFixture.productId).Result;

            Assert.Equal(imageCount + 1, newImages.Result.Count);
        }
예제 #28
0
 private static void SaveImageFileWithRetry(ImageFile imageFile, string imgDestPath, int retryCount = 3)
 {
     for (var retry = 1; retry <= retryCount; retry++)
     {
         try
         {
             imageFile.Save(imgDestPath);
             break;
         }
         catch (IOException) when(retry < retryCount)
         {
             Thread.Sleep(1000);
         }
         catch (IOException eio) when(retry == retryCount)
         {
             throw new Exception($"Error in ACTransit.Framework.Imaging.SaveImageFileWithRetry - Exceeded {retryCount} attempts to save the file", eio);
         }
         catch (Exception ex)
         {
             throw new Exception("Error in ACTransit.Framework.Imaging.SaveImageFileWithRetry", ex);
         }
     }
 }
예제 #29
0
    public void ShowContent(ImageFile file)
    {
        if (activeImage == file)
        {
            return;
        }
        activeImage = file;

        var url = file.url;

        if (App.cache.HasCached(url))
        {
            url = App.cache.GetCachedPath(url);
        }

        rawImage.canvasRenderer.SetAlpha(0);

        if (loadImage != null)
        {
            StopCoroutine(loadImage);
        }
        StartCoroutine(Load(url));
    }
예제 #30
0
	private static long SkipDataSegment (ImageFile file)
	{
		long position = file.Tell;

		// skip sos maker
		if (file.ReadBlock (2).ToUInt () != 0xFFDA)
			throw new Exception (String.Format ("Not a data segment at position: {0}", position));

		while (true) {
			if (0xFF == (byte) file.ReadBlock (1)[0]) {
				byte maker = (byte) file.ReadBlock (1)[0];

				if (maker != 0x00 && (maker <= 0xD0 || maker >= 0xD7))
					break;
			}
		}

		long length = file.Tell - position - 2;

		System.Console.WriteLine ("Data segment of length {0} found at {1}", length, position);

		return length;
	}
예제 #31
0
	public static Pixbuf GenerateThumbnail (System.Uri uri, ImageFile img)
	{
		Pixbuf thumbnail = null;

		if (img is FSpot.IThumbnailContainer) {
			try {
				thumbnail = ((FSpot.IThumbnailContainer)img).GetEmbeddedThumbnail ();
			} catch (Exception e) {
				Log.DebugFormat ("Exception while loading embedded thumbail {0}", e.ToString ());
			}
		}

		// Save embedded thumbnails in a silightly invalid way so that we know to regnerate them later.
		if (thumbnail != null) {
			PixbufUtils.SaveAtomic (thumbnail, FSpot.ThumbnailGenerator.ThumbnailPath (uri), 
						"png", new string [] { null} , new string [] { null});
			//FIXME with gio, set it to uri time minus a few sec
			System.IO.File.SetLastWriteTime (FSpot.ThumbnailGenerator.ThumbnailPath (uri), new DateTime (1980, 1, 1));
		} else 
			thumbnail = FSpot.ThumbnailGenerator.Create (uri);
		
		return thumbnail;
	}
예제 #32
0
        public bool Convert(FilterRequest req)
        {
            Uri dest_uri = req.TempUri(System.IO.Path.GetExtension(req.Current.LocalPath));

            using (ImageFile img = ImageFile.Create(req.Current)) {
                using (Pixbuf in_pixbuf = img.Load()) {
                    using (Pixbuf out_pixbuf = PixbufUtils.UnsharpMask(in_pixbuf, radius, amount, threshold)) {
                        string destination_extension = Path.GetExtension(dest_uri.LocalPath);

                        if (Path.GetExtension(req.Current.LocalPath).ToLower() == Path.GetExtension(dest_uri.LocalPath).ToLower())
                        {
                            using (Stream output = File.OpenWrite(dest_uri.LocalPath)) {
                                img.Save(out_pixbuf, output);
                            }
                        }
                        else if (destination_extension == ".jpg")
                        {
                            // FIXME this is a bit of a nasty hack to work around
                            // the lack of being able to change the path in this filter
                            // and the lack of proper metadata copying yuck
                            Exif.ExifData exif_data;

                            exif_data = new Exif.ExifData(req.Current.LocalPath);

                            PixbufUtils.SaveJpeg(out_pixbuf, dest_uri.LocalPath, 90, exif_data);
                        }
                        else
                        {
                            throw new NotImplementedException(String.Format(Catalog.GetString("No way to save files of type \"{0}\""), destination_extension));
                        }
                    }
                }
            }

            req.Current = dest_uri;
            return(true);
        }
예제 #33
0
        void    Plot(int _roughnessIndex, int _row, int _column, ImageFile _image, PanelOutput _panel, Label _label)
        {
            _image.Clear(float4.One);

            // Determine range first
            int W = m_results.GetLength(0);

            float[] values = new float[W];
            float   min    = float.MaxValue;
            float   max    = -float.MaxValue;

            for (int X = 0; X < W; X++)
            {
                LTC    ltc  = m_results[_roughnessIndex, X];
                double term = ltc.invM[_row, _column];
                term     /= ltc.invM[1, 1];                             // Normalize by central term
                values[X] = (float)term;
                min       = Math.Min(min, values[X]);
                max       = Math.Max(max, values[X]);
            }
            float2 rangeY = float2.UnitY;

            rangeY.x = Math.Min(rangeY.x, min);
            rangeY.y = Math.Max(rangeY.y, max);

            // Plot graph and update UI
            float2 rangeX = new float2(0, 1);

            _image.PlotGraph(new float4(0, 0, 0, 1), rangeX, rangeY, ( float _X ) => {
                int X = Math.Min(W - 1, (int)(W * _X));
                return(values[X]);
            });
            _image.PlotAxes(float4.UnitW, rangeX, rangeY, 0.1f, 0.1f * (rangeY.y - rangeY.x));
            _label.Text     = "Coefficient m" + _row + "" + _column + " - Range [" + rangeY.x + ", " + rangeY.y + "]";
            _panel.m_bitmap = _image.AsBitmap;
            _panel.Refresh();
        }
예제 #34
0
        private static byte[] saveToByteArray(ImageFile replacementImageFile, Bitmap image)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            using (var stream = new MemoryStream())
            {
                try
                {
                    if (replacementImageFile.FullPath.EndsWith(".jpg", Str.Comparison))
                    {
                        var codec         = codecs.First(_ => _.MimeType == "image/jpeg");
                        var encoderParams = new EncoderParameters
                        {
                            Param = { [0] = new EncoderParameter(Encoder.Quality, (long)90) }
                        };

                        image.Save(stream, codec, encoderParams);
                    }
                    else if (replacementImageFile.FullPath.EndsWith(".png", Str.Comparison))
                    {
                        image.Save(stream, ImageFormat.Png);
                    }
                    else
                    {
                        throw new NotSupportedException("only .png .jpg extensions are supported");
                    }
                }
                catch
                {
                    Console.WriteLine("Failed to save " + replacementImageFile.FullPath);
                    return(null);
                }

                var bytes = stream.ToArray();
                return(bytes);
            }
        }
예제 #35
0
        public void Load(SafeUri uri)
        {
            if (is_disposed)
            {
                return;
            }

            //First, send a thumbnail if we have one
            if ((thumb = App.Instance.Container.Resolve <IThumbnailService> ().TryLoadThumbnail(uri, ThumbnailSize.Large)) != null)
            {
                pixbuf_orientation = ImageOrientation.TopLeft;
                EventHandler <AreaPreparedEventArgs> prep = AreaPrepared;
                if (prep != null)
                {
                    prep(this, new AreaPreparedEventArgs(true));
                }
                EventHandler <AreaUpdatedEventArgs> upd = AreaUpdated;
                if (upd != null)
                {
                    upd(this, new AreaUpdatedEventArgs(new Rectangle(0, 0, thumb.Width, thumb.Height)));
                }
            }

            using (var image_file = ImageFile.Create(uri)) {
                image_stream       = image_file.PixbufStream();
                pixbuf_orientation = image_file.Orientation;
            }

            loading = true;
            // The ThreadPool.QueueUserWorkItem hack is there cause, as the bytes to read are present in the stream,
            // the Read is CompletedAsynchronously, blocking the mainloop
            image_stream.BeginRead(buffer, 0, count, delegate(IAsyncResult r) {
                ThreadPool.QueueUserWorkItem(delegate {
                    HandleReadDone(r);
                });
            }, null);
        }
예제 #36
0
        public Stream Transfer(int pageNumber, WiaBackgroundEventLoop eventLoop, string format)
        {
            if (eventLoop.GetSync(wia => wia.Item) == null)
            {
                return(null);
            }
            if (pageNumber == 1)
            {
                // The only downside of the common dialog is that it steals focus.
                // If this is the first page, then the user has just pressed the scan button, so that's not
                // an issue and we can use it and get the benefits of progress display and immediate cancellation.
                ImageFile imageFile = eventLoop.GetSync(wia =>
                                                        (ImageFile) new CommonDialogClass().ShowTransfer(wia.Item, format));
                if (imageFile == null)
                {
                    return(null);
                }
                return(new MemoryStream((byte[])imageFile.FileData.get_BinaryData()));
            }
            // For subsequent pages, we don't want to take focus in case the user has switched applications,
            // so we use the custom form.
            var form = formFactory.Create <FScanProgress>();

            form.PageNumber = pageNumber;
            form.EventLoop  = eventLoop;
            form.Format     = format;
            form.ShowDialog();
            if (form.Exception != null)
            {
                WiaApi.ThrowDeviceError(form.Exception);
            }
            if (form.DialogResult == DialogResult.Cancel)
            {
                return(null);
            }
            return(form.ImageStream);
        }
예제 #37
0
        public void CapturePic(int iQcInfoID)
        {
            InitSDK();
            base.Hide();//
            SetLogin();
            string strDirectoryName = Common.BaseFile + "weightPic\\";

            if (!Directory.Exists(strDirectoryName))
            {
                Directory.CreateDirectory(strDirectoryName);
            }
            string strfileImage = SDKCommon.CaptureJPEGPicture(strDirectoryName, iQcInfoID, Common.Channel);

            //上传图片
            List <string> list = new List <string>();

            //得到图片的路径
            string path = Common.BaseFile + "weightPic\\" + strfileImage;

            ImageFile.UpLoadFile(path, Common.SaveFiel); //上传图片到指定路径

            ImageFile.Delete(path);                      //上传完成后,删除图片
            //保存图片信息
        }
예제 #38
0
        public string saveImage(ImageFile image)
        {
            string response = null;
            string data     = null;

            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(
                    typeof(ImageFile));
                MemoryStream mem = new MemoryStream();
                ser.WriteObject(mem, image);
                data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
                WebClient webClient = new WebClient();
                webClient.Headers["Content-type"] = "application/json";
                webClient.Encoding = Encoding.UTF8;
                response           = webClient.UploadString(BASE_URL + "saveImage", "POST", data);

                return(response);
            }
            catch
            {
                return(null);
            }
        }
예제 #39
0
        protected void btnSub_Click(object sender, EventArgs e)
        {
            string role     = Convert.ToString(Session["Level"]);
            int    LoggedID = Convert.ToInt32(Session["ID"]);

            if (role.ToLower().Equals("manager"))
            {
                TeamServiceClient teamClient = new TeamServiceClient();
                Team _team = new Team();
                _team.foreignID  = LoggedID;
                _team.Type       = txtCategory.Value;
                _team.Name       = txtName.Value;
                _team.Desc       = txtDesc.Value;
                _team.NumPlayers = Convert.ToInt32(txtNumPlayer.Text);

                int TeamID = teamClient.AddTeam(_team);
                makeDirectory(Convert.ToString(TeamID));

                string res = ImportData(flExcel, TeamID);
                if (res.ToLower().Contains("success"))
                {
                    //Alert players loaded succesfully
                }
                //Upload Team Image
                ImageFile img = new ImageFile();
                img = UploadFile(flImage, Convert.ToString(TeamID), "Team_Images", "Teams"); //Upload Event Main's Image to client directory
                FileClient fc     = new FileClient();
                string     res1   = fc.saveTeamImage(img);                                   //Upload Event Main's Image to Database
                string     number = res1;
                Response.Redirect("Index.aspx");
            }
            else
            {
                Response.Redirect("LoginPage.aspx");
            }
        }
예제 #40
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try {
                m_device.Init(panelOutput3D.Handle, false, true);

                m_Shader_renderWall    = new Shader(m_device, new System.IO.FileInfo("./Shaders/RenderWall.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", null);
                m_Shader_renderGBuffer = new Shader(m_device, new System.IO.FileInfo("./Shaders/RenderGBuffer.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", null);
                m_Shader_renderScene   = new Shader(m_device, new System.IO.FileInfo("./Shaders/RenderScene.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS", null);

                m_CB_Main   = new ConstantBuffer <CB_Main>(m_device, 0);
                m_CB_Camera = new ConstantBuffer <CB_Camera>(m_device, 1);

                using (ImageFile blueNoise = new ImageFile(new System.IO.FileInfo("BlueNoise64x64.png"))) {
                    m_Tex_BlueNoise = new Texture2D(m_device, new ImagesMatrix(new ImageFile[, ] {
                        { blueNoise }
                    }), COMPONENT_FORMAT.UNORM);
                }
                m_Tex_Wall    = new Texture2D(m_device, 64, 64, 1, 1, PIXEL_FORMAT.RGBA8, COMPONENT_FORMAT.AUTO, false, false, null);
                m_Tex_GBuffer = new Texture2D(m_device, m_device.DefaultTarget.Width, m_device.DefaultTarget.Height, 2, 1, PIXEL_FORMAT.RGBA16F, COMPONENT_FORMAT.AUTO, false, false, null);
            } catch (Exception _e) {
                MessageBox.Show(this, "Exception: " + _e.Message, "Path Tracing Test", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            m_startTime = DateTime.Now;

            // Initialize camera
            m_camera.CreatePerspectiveCamera(60.0f * (float)Math.PI / 180.0f, (float)panelOutput3D.Width / panelOutput3D.Height, 0.01f, 10.0f);
            m_manipulator.Attach(panelOutput3D, m_camera);
            m_manipulator.InitializeCamera(new float3(0, 0, -0.5f), float3.Zero, float3.UnitY);
            m_camera.CameraTransformChanged += m_camera_CameraTransformChanged;
            m_camera_CameraTransformChanged(null, EventArgs.Empty);

            Application.Idle += Application_Idle;
        }
예제 #41
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var q = new Models.Question
            {
                Text                                        = Question,
                QuestionForDate                             = Date,
                Image                                       = ImageFile != null?ImageFile.GetBase64HtmlString() : string.Empty,
                                               Alternatives = new List <Models.Alternative>
                {
                    new Models.Alternative
                    {
                        Description = Alternative1,
                        IsCorrect   = IsCirrect1
                    },
                    new Models.Alternative
                    {
                        Description = Alternative2,
                        IsCorrect   = IsCirrect2
                    },
                    new Models.Alternative
                    {
                        Description = Alternative3,
                        IsCorrect   = IsCirrect3
                    }
                }
            };

            await _questionService.AddQuestion(q);

            return(RedirectToPage("/Admin/Questions"));
        }
예제 #42
0
        private static Image MultiplyBlend(ImageFile image, ImageFile mask)
        {
            if (image.Width != mask.Width || image.Height != mask.Height)
            {
                throw new ArgumentException();
            }
            // Using 32bit color
            const int BytesPerPixel = 4;

            var aArgb  = Imaging.ImageConverter.GetA8R8G8B8(image);
            var bArgb  = Imaging.ImageConverter.GetA8R8G8B8(mask);
            var result = new byte[aArgb.Length];

            for (var i = 0; i < aArgb.Length; i += BytesPerPixel)
            {
                for (var j = 0; j < 3; ++j)     // Only blend RGB
                {
                    result[i + j] = (byte)((aArgb[i + j] * bArgb[i + j]) / 255);
                }
                result[i + 3] = aArgb[i + 3];  // Preserve alpha
            }

            Image output;

            unsafe
            {
                fixed(byte *p = result)
                {
                    var ptr = (IntPtr)p;

                    using (var tempImage = new Bitmap(image.Width, image.Height, image.Width * BytesPerPixel, PixelFormat.Format32bppArgb, ptr))
                        output = new Bitmap(tempImage);
                }
            }
            return(output);
        }
예제 #43
0
        public string saveImage(ImageFile imageUp)
        {
            //trim string location
            String imgLocation = imageUp.Location;
            string output      = imgLocation.Substring(imgLocation.IndexOf('E')); //trim string path from Event

            try
            {
                using (EventrixDBDataContext db = new EventrixDBDataContext())
                {
                    var query = from image in db.EventImages where image.EventImageId.Equals(imageUp.ImageId) select image;
                    if (query.Count() == 0)
                    {
                        EventImage fileToSave = new EventImage();
                        fileToSave.Name         = imageUp.ImageName;
                        fileToSave.Location     = output;
                        fileToSave.Size         = (int)imageUp.FileSize;
                        fileToSave.DateUploaded = imageUp.DateUploaded;
                        fileToSave.ContentType  = imageUp.ContentType;
                        fileToSave.EventID      = Convert.ToInt32(imageUp.EventID);
                        db.EventImages.InsertOnSubmit(fileToSave);
                        db.SubmitChanges();
                    }
                    else
                    if (query.Count() == 1)
                    {
                        return("File Exist");
                    }
                }
                return("Success File Uploaded");
            }
            catch (Exception)
            {
                return("Failed Upload Failed");
            }
        }
예제 #44
0
        protected void ScanPhotoDirectory(ImportController controller, SafeUri uri, PhotoList photo_list)
        {
            var enumerator = new RecursiveFileEnumerator(uri)
            {
                Recurse        = controller.RecurseSubdirectories,
                CatchErrors    = true,
                IgnoreSymlinks = true
            };
            var infos = new List <FileImportInfo> ();

            foreach (var file in enumerator)
            {
                if (ImageFile.HasLoader(new SafeUri(file.Uri.ToString(), true)))
                {
                    infos.Add(new FileImportInfo(new SafeUri(file.Uri.ToString(), true)));
                }

                if (infos.Count % 10 == 0 || infos.Count < 10)
                {
                    var to_add = infos;                     // prevents race condition
                    ThreadAssist.ProxyToMain(() => photo_list.Add(to_add.ToArray()));
                    infos = new List <FileImportInfo> ();
                }

                if (!run_photoscanner)
                {
                    return;
                }
            }

            if (infos.Count > 0)
            {
                var to_add = infos;                 // prevents race condition
                ThreadAssist.ProxyToMain(() => photo_list.Add(to_add.ToArray()));
            }
        }
        public ActionResult Delete(string filename, FormCollection collection)
        {
            try
            {
                var fullPath = string.Format("{0}/{1}", _imagePath, filename);
                var path     = Server.MapPath(fullPath);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                ImageFile file = new ImageFile()
                {
                    Filename = filename,
                };
                ViewBag.Error = e.Message;

                return(View(file));
            }
        }
예제 #46
0
        /// <summary>
        /// 'Date Taken Original' value from image EXIF data. Avoids loading the whole image file into memory.
        /// </summary>
        /// <param name="path">Filepath to image</param>
        /// <returns>'Date Taken Original' value from EXIF converted into DateTime format</returns>
        private static DateTime?GetDateImageWasTaken(string path)
        {
            try
            {
                ImageFile imageFile           = ImageFile.FromFile(path);
                var       datetimeOriginal    = imageFile.Properties.FirstOrDefault <ExifProperty>(x => x.Tag == ExifTag.DateTimeOriginal).Value;
                string    datetimeOriginaltxt = datetimeOriginal.ToString();

                if (DateTime.TryParse(datetimeOriginaltxt, out DateTime dtOriginal))
                {
                    return(dtOriginal);
                }

                //Unable to get date
                return(null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed reading EXIF data...");
            }

            //Unable to extract EXIF data from file
            return(null);
        }
예제 #47
0
        private void ScanDoc()
        {
            CommonDialogClass commonDialogClass = new CommonDialogClass();
            Device            scannerDevice     = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);

            if (scannerDevice != null)
            {
                Item scannnerItem = scannerDevice.Items[1];
                SelectDeviceDocumentHandling(scannerDevice, DeviceDocumentHandling.Feeder);
                AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 30, -50, cmbColorMode.SelectedIndex);
                object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false);
                //picScan.Image = (System.Drawing.Image)scanResult;
                if (scanResult != null)
                {
                    ImageFile image = (ImageFile)scanResult;

                    string fileName = "";

                    var files = Directory.GetFiles(txtPath.Text + "\\temp\\", "*.jpg");


                    try
                    {
                        string f = ((files.Max(p1 => Int32.Parse(Path.GetFileNameWithoutExtension(p1)))) + 1).ToString();
                        fileName = txtPath.Text + "\\temp\\" + f + ".jpg";
                    }
                    catch
                    {
                        fileName = txtPath.Text + "\\temp\\" + "1.jpg";
                    }

                    SaveImageToTiff(image, fileName);
                    picScan.ImageLocation = fileName;
                }
            }
        }
예제 #48
0
        /// <summary>
        /// Handles the <see cref="ButtonBase.Click"/> event for the "Change ID" <see
        /// cref="Button"/> that is associated with the "Image File" list view.</summary>
        /// <param name="sender">
        /// The <see cref="Object"/> where the event handler is attached.</param>
        /// <param name="args">
        /// A <see cref="RoutedEventArgs"/> object containing event data.</param>
        /// <remarks><para>
        /// <b>OnFileId</b> displays a <see cref="Dialog.ChangeIdentifier"/> dialog for the first
        /// selected item in the "Image File" list view.
        /// </para><para>
        /// If the user made any changes, <b>OnFileId</b> propagates them to the current <see
        /// cref="ImageSection"/>, redisplays all images, and sets the <see
        /// cref="SectionTabItem.DataChanged"/> flag.</para></remarks>

        private void OnFileId(object sender, RoutedEventArgs args)
        {
            args.Handled = true;

            // retrieve selected image file, if any
            ImageFile file = FileList.SelectedItem as ImageFile;

            if (file == null)
            {
                return;
            }

            // let user enter new image file ID
            var files  = MasterSection.Instance.Images.ImageFiles;
            var dialog = new Dialog.ChangeIdentifier(file.Id,
                                                     Global.Strings.TitleImageIdChange, files.ContainsKey, true);

            dialog.Owner = MainWindow.Instance;
            if (dialog.ShowDialog() != true)
            {
                return;
            }

            // retrieve new image file ID
            string id = String.Intern(dialog.Identifier);

            // change existing ID references
            if (!SectionTabItem.ProcessAllIdentifiers(files, file.Id, id))
            {
                return;
            }

            // broadcast data changes
            FileList.Items.Refresh();
            SectionTab.DataChanged = true;
        }
예제 #49
0
        public ImageInfo CollectImageInfo(ImageFile imageFile)
        {
            Image image = new Bitmap(imageFile.FilePath);

            ImageInfo imageInfo = new ImageInfo();

            imageInfo.ImageFileID = imageFile.ID;


            try
            {
                imageInfo.Longitude   = GetLongitude(image);
                imageInfo.Latitiude   = GetLatitiude(image);
                imageInfo.DateCreated = GetDateCreated(image);
            }
            catch (Exception)
            {
                Console.WriteLine("No gps data on image: " + imageFile.FileName);
            }

            image.Dispose();

            return(imageInfo);
        }
        public ActionResult Create(Banner banner, HttpPostedFileBase Images)
        {
            if (ModelState.IsValid)
            {
                if (!Directory.Exists(Server.MapPath("~/Admin/Images/Banner")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Admin/Images/Banner"));
                }
                if (Images != null)
                {
                    Images.SaveAs(Server.MapPath("~/Admin/Images/Banner/" + Images.FileName));
                    ImageFile file = new ImageFile
                    {
                        Name         = Images.FileName,
                        Size         = Images.ContentLength / 10000,
                        path         = "~/Admin/Images/Banner/" + Images.FileName,
                        Type         = "Image",
                        UploadedBy   = "Admin",
                        UploadedDate = DateTime.Now
                    };
                    db.ImageFile.Add(file);
                    db.SaveChanges();

                    ImageFile image = db.ImageFile.OrderByDescending(m => m.Id).FirstOrDefault();
                    banner.Image = image;
                }

                db.Banners.Add(banner);
                db.SaveChanges();


                return(RedirectToAction("Index"));
            }

            return(View(banner));
        }
            public void Linearize(string name)
            {
                GammaTable table = new GammaTable(new ushort [] { 0x0000, 0x0000, 0x0000, 0x0000 });
                Profile    link  = new Profile(IccColorSpace.Rgb, new GammaTable [] { table, table, table });

                string path = CreateFile(name, 32);

                using (FilterRequest req = new FilterRequest(path)) {
                    ColorFilter filter = new ColorFilter();
                    filter.DeviceLink = link;
                    Assert.IsTrue(filter.Convert(req), "Filter failed to operate");
                    req.Preserve(req.Current);
                    Assert.IsTrue(System.IO.File.Exists(req.Current.LocalPath),
                                  "Error: Did not create " + req.Current);
                    Assert.IsTrue(new FileInfo(req.Current.LocalPath).Length > 0,
                                  "Error: " + req.Current + "is Zero length");
                    using (ImageFile img = ImageFile.Create(req.Current)) {
                        Pixbuf pixbuf = img.Load();
                        Assert.IsNotNull(pixbuf);
                        // We linearized to all black so this should pass the gray test
                        Assert.IsTrue(PixbufUtils.IsGray(pixbuf, 1), "failed to linearize" + req.Current);
                    }
                }
            }
예제 #52
0
        public void UnAssignImageFromProductForStore()
        {
            // Arrange
            var images = Client.GetImagesForProduct(productId).Result;
            var imageCount = images.Result == null ? 0 : images.Result.Count;
            var imagesForStore = Client.GetImagesForProductForStore(productId, storeId1).Result;
            var filePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Images\\100001\\") + "04.jpg";
            var imageFile = new ImageFile
            {
                file_content = File.ReadAllBytes(filePath),
                file_mime_type = "image/jpeg",
                file_name = "100001_04"
            };
            var response1 = Client.AddImageToProduct(productId, imageFile).Result;
            var imageId = response1.Result;
            var imageInfo = Client.GetImageInfoForProduct(productId, imageId).Result.Result;
            imageInfo.types.Add(ImageType.image);
            imageInfo.types.Add(ImageType.small_image);
            imageInfo.types.Add(ImageType.thumbnail);
            var response2 = Client.UpdateImageInfoForProduct(productId, imageId, imageInfo).Result;

            // Act
            var response3 = Client.UnAssignImageFromProductForStore(productId, storeId1, imageId).Result;
            var updatedImages = Client.GetImagesForProduct(productId).Result;
            var updatedImagesForStore1 = Client.GetImagesForProductForStore(productId, storeId1).Result;

            // Assert
            Assert.IsFalse(response3.HasErrors, response3.ErrorString);
            Assert.AreEqual(imageCount + 1, updatedImagesForStore1.Result.Count);
            Assert.AreEqual(imageCount + 1, updatedImages.Result.Count);
            var imageInfo2 = Client.GetImageInfoForProduct(productId, imageId).Result.Result;
            Assert.AreEqual(3, imageInfo2.types.Count);
            var imageInfo3 = Client.GetImageInfoForProductForStore(productId, storeId1, imageId).Result.Result;
            Assert.AreEqual(0, imageInfo3.types.Count);
        }
예제 #53
0
        public void UnassignImageFromProduct()
        {
            // Arrange
            var images = Client.GetImagesForProduct(productId).Result;
            var imageCount = images.Result == null ? 0 : images.Result.Count;

            // Act
            var filePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Images\\100001\\") + "03.jpg";
            var imageFile = new ImageFile
            {
                file_content = File.ReadAllBytes(filePath),
                file_mime_type = "image/jpeg",
                file_name = "100001_03"
            };
            var response = Client.AddImageToProduct(productId, imageFile).Result;
            var newImages = Client.GetImagesForProduct(productId).Result;
            var response2 = Client.UnassignImageFromProduct(productId, response.Result).Result;
            var updatedImages = Client.GetImagesForProduct(productId).Result;

            // Assert
            Assert.IsFalse(response.HasErrors, response.ErrorString);
            Assert.AreEqual(imageCount + 1, newImages.Result.Count);
            // Only when the image is not used in any stores, then it gets deleted
            Assert.AreEqual(imageCount, updatedImages.Result.Count);
        }
예제 #54
0
파일: Form1.cs 프로젝트: Patapom/GodComplex
        void TestBuildImage( BUILD_TESTS _type )
        {
            try {
                switch ( _type ) {
                    case BUILD_TESTS.FILL_PIXEL:
                        // Write pixel per pixel
                        m_imageFile = new ImageFile( 378, 237, ImageFile.PIXEL_FORMAT.RGB16, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
                        for ( uint Y=0; Y < m_imageFile.Height; Y++ ) {
                            for ( uint X=0; X < m_imageFile.Width; X++ ) {
                                float	R = (float) (1+X) / m_imageFile.Width;
                                float	G = (float) (1+Y) / m_imageFile.Height;
                                m_imageFile[X,Y] = new float4( R, G, 1.0f-0.5f*(R+G), 1 );
                            }
                        }
                        break;

                    case BUILD_TESTS.FILL_SCANLINE:
                        // Write scanline per scanline
                        m_imageFile = new ImageFile( 378, 237, ImageFile.PIXEL_FORMAT.RGB16, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
                        float4[]	scanline = new float4[m_imageFile.Width];
                        for ( uint Y=0; Y < m_imageFile.Height; Y++ ) {
                            for ( uint X=0; X < m_imageFile.Width; X++ ) {
                                float	R = 1.0f - (float) (1+X) / m_imageFile.Width;
                                float	G = (float) (1+Y) / m_imageFile.Height;
                                scanline[X].Set( R, G, 1.0f-0.5f*(R+G), 1 );
                            }

                            m_imageFile.WriteScanline( Y, scanline );
                        }
                        break;

                    // Buddhabrot
                    case BUILD_TESTS.ADDITIVE_BUDDHABROT: {
                        m_imageFile = new ImageFile( 378, 237, ImageFile.PIXEL_FORMAT.RGB16, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
                        uint	W = m_imageFile.Width;
                        uint	H = m_imageFile.Height;
                        float2	Z, Z0;
                        int		iterations = 50;
                        float4	inc = (1.0f / iterations) * float4.One;
                        float	zoom = 2.0f;
                        float	invZoom = 1.0f / zoom;

            #if DIRECT_WRITE		// Either directly accumulate to image
                        for ( uint Y=0; Y < H; Y++ ) {
                            Z0.y = zoom * (Y - 0.5f * H) / H;
                            for ( uint X=0; X < W; X++ ) {
                                Z0.x = zoom * (X - 0.5f * W) / H;
                                Z = Z0;
                                for ( int i=0; i < iterations; i++ ) {
                                    Z.Set( Z.x*Z.x - Z.y*Z.y + Z0.x, 2.0f * Z.x * Z.y + Z0.y );

                                    int	Nx = (int) (invZoom * Z.x * H + 0.5f * W);
                                    int	Ny = (int) (invZoom * Z.y * H + 0.5f * H);
                                    if ( Nx >= 0 && Nx < W && Ny >= 0 && Ny < H ) {
            // 										float4	tagada = (float4) m_imageFile[(uint)Nx,(uint)Ny];
            // 										tagada += inc;
            // 										m_imageFile[(uint)Nx,(uint)Ny] = tagada;
             										m_imageFile.Add( (uint)Nx, (uint)Ny, inc );
                                    }
                                }
                            }
                        }
            #else						// Or accumulate to a temp array and write result (this is obviously faster!)
                        float[,]	accumulators = new float[W,H];
                        for ( uint Y=0; Y < H; Y++ ) {
                            Z0.y = zoom * (Y - 0.5f * H) / H;
                            for ( uint X=0; X < W; X++ ) {
                                Z0.x = zoom * (X - 0.5f * W) / H;
                                Z = Z0;
                                for ( int i=0; i < iterations; i++ ) {
                                    Z.Set( Z.x*Z.x - Z.y*Z.y + Z0.x, 2.0f * Z.x * Z.y + Z0.y );

                                    int	Nx = (int) (invZoom * Z.x * H + 0.5f * W);
                                    int	Ny = (int) (invZoom * Z.y * H + 0.5f * H);
                                    if ( Nx >= 0 && Nx < W && Ny >= 0 && Ny < H )
                                        accumulators[Nx, Ny] += inc.x;
                                }
                            }
                        }
                        float4	temp = new float4();
                        for ( uint Y=0; Y < H; Y++ ) {
                            for ( uint X=0; X < W; X++ ) {
                                float	a = accumulators[X,Y];
                                temp.Set( a, a, a, 1 );
                                m_imageFile[X,Y] = temp;
                            }
                        }
            #endif
                    }
                    break;

                    case BUILD_TESTS.STRESS_BUILD:

                        ImageFile.PIXEL_FORMAT[]	formats = new ImageFile.PIXEL_FORMAT[] {
                            ImageFile.PIXEL_FORMAT.R8,
                            ImageFile.PIXEL_FORMAT.RG8,
                            ImageFile.PIXEL_FORMAT.RGB8,
                            ImageFile.PIXEL_FORMAT.RGBA8,
                            ImageFile.PIXEL_FORMAT.R16,
            //							ImageFile.PIXEL_FORMAT.RG16,
                            ImageFile.PIXEL_FORMAT.RGB16,
                            ImageFile.PIXEL_FORMAT.RGBA16,
                            ImageFile.PIXEL_FORMAT.R16F,
                            ImageFile.PIXEL_FORMAT.RG16F,
                            ImageFile.PIXEL_FORMAT.RGB16F,
                            ImageFile.PIXEL_FORMAT.RGBA16F,
                            ImageFile.PIXEL_FORMAT.R32F,
            //							ImageFile.PIXEL_FORMAT.RG32F,
                            ImageFile.PIXEL_FORMAT.RGB32F,
                            ImageFile.PIXEL_FORMAT.RGBA32F,
                        };
                        Random	RNG = new Random( 1 );
                        for ( int i=0; i < 1000; i++ ) {

                            uint	W = 100 + (uint) (1000 * RNG.NextDouble());
                            uint	H = 100 + (uint) (1000 * RNG.NextDouble());
                            ImageFile.PIXEL_FORMAT	format = formats[RNG.Next( formats.Length-1 )];
                            m_imageFile = new ImageFile( W, H,format, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
                            m_imageFile.Dispose();
                        }

                        m_imageFile = new ImageFile( 1000, 1000, ImageFile.PIXEL_FORMAT.RGBA8, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );
                        m_imageFile.Clear( new float4( 0, 1, 0.2f, 1 ) );
                        break;

                }

                panelBuild.Bitmap = m_imageFile.AsBitmap;

            } catch ( Exception _e ) {
                MessageBox.Show( "Error: " + _e.Message );
            }
        }
예제 #55
0
파일: Form1.cs 프로젝트: Patapom/GodComplex
        protected void TestConvertLDR2HDR( System.IO.FileInfo[] _LDRImageFileNames, bool _responseCurveOnly, bool _RAW )
        {
            try {

                // Load the LDR images
                List< ImageFile >	LDRImages = new List< ImageFile >();
                foreach ( System.IO.FileInfo LDRImageFileName in _LDRImageFileNames )
                    LDRImages.Add( new ImageFile( LDRImageFileName ) );

                // Retrieve the shutter speeds
                List< float >	shutterSpeeds = new List< float >();
                foreach ( ImageFile LDRImage in LDRImages ) {
                    shutterSpeeds.Add( LDRImage.Metadata.ExposureTime );
                }

                // Retrieve filter type
                Bitmap.FILTER_TYPE	filterType = Bitmap.FILTER_TYPE.NONE;
                if ( radioButtonFilterNone.Checked ) {
                     filterType = Bitmap.FILTER_TYPE.NONE;
                } else if ( radioButtonFilterGaussian.Checked ) {
                     filterType = Bitmap.FILTER_TYPE.SMOOTHING_GAUSSIAN;
                } else if ( radioButtonFilterGaussian2Pass.Checked ) {
                     filterType = Bitmap.FILTER_TYPE.SMOOTHING_GAUSSIAN_2_PASSES;
                } else if ( radioButtonFilterTent.Checked ) {
                     filterType = Bitmap.FILTER_TYPE.SMOOTHING_TENT;
                } else if ( radioButtonFilterCurveFitting.Checked ) {
                     filterType = Bitmap.FILTER_TYPE.GAUSSIAN_PLUS_CURVE_FITTING;
                }

            // Check EXR save is working!
            // ImageFile	pipo = new ImageFile();
            // 			pipo.ConvertFrom( LDRImages[0], ImageFile.PIXEL_FORMAT.RGB32F );
            // pipo.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromJPG\Result.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_DEFAULT );

            // Check bitmap->tone mapped image file is working
            // {
            // 	Bitmap	tempBitmap = new Bitmap();
            // 	List< float >	responseCurve = new List< float >( 256 );
            // 	for ( int i=0; i < 256; i++ )
            // 		responseCurve.Add( (float) (Math.Log( (1+i) / 256.0 ) / Math.Log(2)) );
            // 	tempBitmap.LDR2HDR( new ImageFile[] { LDRImages[4] }, new float[] { 1.0f }, responseCurve, 1.0f );
            //
            // 	ImageFile	tempHDR = new ImageFile();
            // 	tempBitmap.ToImageFile( tempHDR, new ColorProfile( ColorProfile.STANDARD_PROFILE.LINEAR ) );
            //
            // 	ImageFile	tempToneMappedHDR = new ImageFile();
            // 	tempToneMappedHDR.ToneMapFrom( tempHDR,( float3 _HDRColor, ref float3 _LDRColor ) => {
            // 		// Just do gamma un-correction, don't care about actual HDR range...
            // 		_LDRColor.x = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.x ), 1.0f / 2.2f );	// Here we need to clamp negative values that we sometimes get in EXR format
            // 		_LDRColor.y = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.y ), 1.0f / 2.2f );	//  (must be coming from the log encoding I suppose)
            // 		_LDRColor.z = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.z ), 1.0f / 2.2f );
            // 	} );
            //
            // 	panel1.Bitmap = tempToneMappedHDR.AsBitmap;
            // 	return;
            // }

                //////////////////////////////////////////////////////////////////////////////////////////////
                // Build the HDR device-independent bitmap
            //				uint bitsPerPixel = _RAW ? 12U : 8U;
            uint	bitsPerPixel = _RAW ? 8U : 8U;
            float	quality = _RAW ? 3.0f : 3.0f;

                Bitmap.HDRParms	parms = new Bitmap.HDRParms() {
                    _inputBitsPerComponent = bitsPerPixel,
                    _luminanceFactor = 1.0f,
                    _curveSmoothnessConstraint = 1.0f,
                    _quality = quality,
                    _responseCurveFilterType = filterType
                };

                ImageUtility.Bitmap	HDRImage = new ImageUtility.Bitmap();

            //				HDRImage.LDR2HDR( LDRImages.ToArray(), shutterSpeeds.ToArray(), parms );

                // Compute response curve
                List< float >	responseCurve = new List< float >();
                Bitmap.ComputeCameraResponseCurve( LDRImages.ToArray(), shutterSpeeds.ToArray(), parms._inputBitsPerComponent, parms._curveSmoothnessConstraint, parms._quality, responseCurve );

                // Filter
                List< float >	responseCurve_filtered = new List< float >();
            //				Bitmap.FilterCameraResponseCurve( responseCurve, responseCurve_filtered, Bitmap.FILTER_TYPE.CURVE_FITTING );
                Bitmap.FilterCameraResponseCurve( responseCurve, responseCurve_filtered, filterType );

            // 				using ( System.IO.FileStream S = new System.IO.FileInfo( "../../responseCurve3.float" ).Create() )
            // 					using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( S ) ) {
            // 						for ( int i=0; i < 256; i++ )
            // 							W.Write( responseCurve[i] );
            // 					}

                // Write info
                string		info = "Exposures:\r\n";
                foreach ( float shutterSpeed in shutterSpeeds )
                    info += " " + shutterSpeed + "s + ";
                info += "\r\nLog2 exposures (EV):\r\n";
                foreach ( float shutterSpeed in shutterSpeeds )
                    info += " " + (float) (Math.Log( shutterSpeed ) / Math.Log(2)) + "EV + ";
                info += "\r\n\r\n";

                if ( _responseCurveOnly ) {
                    //////////////////////////////////////////////////////////////////////////////////////////////
                    // Render the response curve as a graph
             					ImageFile	tempCurveBitmap = new ImageFile( 1024, 768, ImageFile.PIXEL_FORMAT.RGB8, new ColorProfile( ColorProfile.STANDARD_PROFILE.sRGB ) );

                    int			responseCurveSizeMax = responseCurve.Count-1;

                    float2		rangeX = new float2( 0, responseCurveSizeMax+1 );
                    float2		rangeY = new float2( 0, 500 );
                    tempCurveBitmap.Clear( new float4( 1, 1, 1, 1 ) );
            //					tempCurveBitmap.PlotGraphAutoRangeY( red, rangeX, ref rangeY, ( float x ) => {
                    tempCurveBitmap.PlotGraph( red, rangeX, rangeY, ( float x ) => {
                        int		i0 = (int) Math.Min( responseCurveSizeMax, Math.Floor( x ) );
                        int		i1 = (int) Math.Min( responseCurveSizeMax, i0+1 );
                        float	g0 = responseCurve[i0];
                        float	g1 = responseCurve[i1];
                        float	t = x - i0;
            //						return g0 + (g1-g0) * t;
                        return (float) Math.Pow( 2.0f, g0 + (g1-g0) * t );
                    } );
                    tempCurveBitmap.PlotGraph( blue, rangeX, rangeY, ( float x ) => {
                        int		i0 = (int) Math.Min( responseCurveSizeMax, Math.Floor( x ) );
                        int		i1 = (int) Math.Min( responseCurveSizeMax, i0+1 );
                        float	g0 = responseCurve_filtered[i0];
                        float	g1 = responseCurve_filtered[i1];
                        float	t = x - i0;
            //						return g0 + (g1-g0) * t;
                        return (float) Math.Pow( 2.0f, g0 + (g1-g0) * t );
                    } );
            //					tempCurveBitmap.PlotAxes( black, rangeX, rangeY, 8, 2 );

                    info += "• Linear range Y = [" + rangeY.x + ", " + rangeY.y + "]\r\n";

                    rangeY = new float2( -4, 4 );
                    tempCurveBitmap.PlotLogGraphAutoRangeY( black, rangeX, ref rangeY, ( float x ) => {
            //					tempCurveBitmap.PlotLogGraph( black, rangeX, rangeY, ( float x ) => {
                        int		i0 = (int) Math.Min( responseCurveSizeMax, Math.Floor( x ) );
                        int		i1 = (int) Math.Min( responseCurveSizeMax, i0+1 );
                        float	g0 = responseCurve[i0];
                        float	g1 = responseCurve[i1];
                        float	t = x - i0;
            //						return g0 + (g1-g0) * t;
                        return (float) Math.Pow( 2.0f, g0 + (g1-g0) * t );
                    }, -1.0f, 2.0f );
                    tempCurveBitmap.PlotLogGraph( blue, rangeX, rangeY, ( float x ) => {
            //					tempCurveBitmap.PlotLogGraph( black, rangeX, rangeY, ( float x ) => {
                        int		i0 = (int) Math.Min( responseCurveSizeMax, Math.Floor( x ) );
                        int		i1 = (int) Math.Min( responseCurveSizeMax, i0+1 );
                        float	g0 = responseCurve_filtered[i0];
                        float	g1 = responseCurve_filtered[i1];
                        float	t = x - i0;
            //						return g0 + (g1-g0) * t;
                        return (float) Math.Pow( 2.0f, g0 + (g1-g0) * t );
                    }, -1.0f, 2.0f );
                    tempCurveBitmap.PlotLogAxes( black, rangeX, rangeY, -16, 2 );

                    info += "• Log2 range Y = [" + rangeY.x + ", " + rangeY.y + "]\r\n";

             					panelOutputHDR.Bitmap = tempCurveBitmap.AsBitmap;

                } else {
                    //////////////////////////////////////////////////////////////////////////////////////////////
                    // Recompose the HDR image
                    HDRImage.LDR2HDR( LDRImages.ToArray(), shutterSpeeds.ToArray(), responseCurve_filtered, 1.0f );

                    // Display as a tone-mapped bitmap
                    ImageFile	tempHDR = new ImageFile();
                    HDRImage.ToImageFile( tempHDR, new ColorProfile( ColorProfile.STANDARD_PROFILE.LINEAR ) );

                    if ( _RAW ) {
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromRAW\Result.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_DEFAULT );
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromRAW\Result_B44LC.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_B44 | ImageFile.SAVE_FLAGS.SF_EXR_LC );
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromRAW\Result_noLZW.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_NONE );
                    } else {
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromJPG\Result.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_DEFAULT );
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromJPG\Result_B44LC.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_B44 | ImageFile.SAVE_FLAGS.SF_EXR_LC );
                        tempHDR.Save( new System.IO.FileInfo( @"..\..\Images\Out\LDR2HDR\FromJPG\Result_noLZW.exr" ), ImageFile.FILE_FORMAT.EXR, ImageFile.SAVE_FLAGS.SF_EXR_NONE );
                    }

                    ImageFile	tempToneMappedHDR = new ImageFile();
                    tempToneMappedHDR.ToneMapFrom( tempHDR,( float3 _HDRColor, ref float3 _LDRColor ) => {
                        // Just do gamma un-correction, don't care about actual HDR range...
                        _LDRColor.x = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.x ), 1.0f / 2.2f );	// Here we need to clamp negative values that we sometimes get in EXR format
                        _LDRColor.y = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.y ), 1.0f / 2.2f );	//  (must be coming from the log encoding I suppose)
                        _LDRColor.z = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.z ), 1.0f / 2.2f );
                    } );

                    panelOutputHDR.Bitmap = tempToneMappedHDR.AsBitmap;
                }

                textBoxHDR.Text = info;

            } catch ( Exception _e ) {
                MessageBox.Show( "Error: " + _e.Message );

            // Show debug image
            // panelLoad.Bitmap = Bitmap.DEBUG.AsBitmap;
            }
        }
예제 #56
0
파일: Form1.cs 프로젝트: Patapom/GodComplex
        void TestLoadImage( LOADING_TESTS _type )
        {
            try {
                switch ( _type ) {
                    // BMP
                    case LOADING_TESTS.BMP_RGB:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\BMP\RGB8.bmp" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                    case LOADING_TESTS.BMP_RGBA:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\BMP\RGBA8.bmp" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // GIF
                    case LOADING_TESTS.GIF_RGB8P:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\GIF\RGB8P.gif" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // JPG
                    case LOADING_TESTS.JPEG_R8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\JPG\R8.jpg" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                    case LOADING_TESTS.JPEG_RGB8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\JPG\RGB8.jpg" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\JPG\RGB8_ICC.jpg" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // PNG
                            // 8-bits
                    case LOADING_TESTS.PNG_R8P:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\R8P.png" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                    case LOADING_TESTS.PNG_RGB8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\RGB8.png" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\RGB8_SaveforWeb.png" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                    case LOADING_TESTS.PNG_RGBA8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\RGBA8.png" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\RGBA8_SaveforWeb.png" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                            // 16-bits
                    case LOADING_TESTS.PNG_RGB16:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\PNG\RGB16.png" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // TGA
                    // @TODO => Check why I can't retrieve my custom metas!
                    case LOADING_TESTS.TGA_RGB8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TGA\RGB8.tga" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                    case LOADING_TESTS.TGA_RGBA8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TGA\RGBA8.tga" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // TIFF
                            // 8-bits
                    case LOADING_TESTS.TIFF_RGB8:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB8.tif" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB8_ICC.tif" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;
                            // 16-bits
                    case LOADING_TESTS.TIFF_RGB16:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB16.tif" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB16_ICC.tif" ) );
                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    // RAW
                    case LOADING_TESTS.CRW:
                        m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\CRW\CRW_7967.CRW" ) );
            //						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7971.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7971.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7972.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7973.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7974.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7975.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7976.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7977.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7978.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7979.crw" ) );
            // 						m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\LDR2HDR\FromRAW\CRW_7980.crw" ) );

                        panelLoad.Bitmap = m_imageFile.AsBitmap;
                        break;

                    default:
                        // High-Dynamic Range Images
                        switch ( _type ) {
                                // HDR
                            case LOADING_TESTS.HDR_RGBE:
                                m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\HDR\RGB32F.hdr" ) );
                                break;

                                // EXR
                            case LOADING_TESTS.EXR_RGB32F:
             								m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\EXR\RGB32F.exr" ) );
                                break;

                                // TIFF
                            case LOADING_TESTS.TIFF_RGB16F:
                                    // 16-bits floating-point
                                m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB16F.tif" ) );
            //								m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB16F_ICC.tif" ) );
                                break;

            // Pom (2016-11-14) This crashes as FreeImage is not capable of reading 32-bits floating point TIFs but I think I don't care, we have enough formats!
            // 							case LOADING_TESTS.TIFF_RGB32F:
            // 									// 32-bits floating-point
            // 								m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB32F.tif" ) );
            // //							m_imageFile.Load( new System.IO.FileInfo( @"..\..\Images\In\TIFF\RGB32F_ICC.tif" ) );
            // 								break;

                            default:
                                throw new Exception( "Unhandled format!" );
                        }

                        ImageFile	tempLDR = new ImageFile();
                        tempLDR.ToneMapFrom( m_imageFile, ( float3 _HDRColor, ref float3 _LDRColor ) => {
                            // Do nothing (linear space to gamma space without care!)
            //							_LDRColor = _HDRColor;

                            // Just do gamma un-correction, don't care about actual HDR range...
                            _LDRColor.x = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.x ), 1.0f / 2.2f );	// Here we need to clamp negative values that we sometimes get in EXR format
                            _LDRColor.y = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.y ), 1.0f / 2.2f );	//  (must be coming from the log encoding I suppose)
                            _LDRColor.z = (float) Math.Pow( Math.Max( 0.0f, _HDRColor.z ), 1.0f / 2.2f );
                        } );
                        panelLoad.Bitmap = tempLDR.AsBitmap;
                    break;
             				}

                // Write out metadata
                MetaData		MD = m_imageFile.Metadata;
                ColorProfile	Profile = MD.ColorProfile;
                textBoxEXIF.Lines = new string[] {
                    "File Format: " + m_imageFile.FileFormat,
                    "Pixel Format: " + m_imageFile.PixelFormat + (m_imageFile.HasAlpha ? " (ALPHA)" : " (NO ALPHA)"),
                    "",
                    "Profile:",
                    "  • Chromaticities: ",
                    "    R = " + Profile.Chromas.Red.ToString(),
                    "    G = " + Profile.Chromas.Green.ToString(),
                    "    B = " + Profile.Chromas.Blue.ToString(),
                    "    W = " + Profile.Chromas.White.ToString(),
                    "    Recognized chromaticities = " + Profile.Chromas.RecognizedChromaticity,
                    "  • Gamma Curve: " + Profile.GammaCurve.ToString(),
                    "  • Gamma Exponent: " + Profile.GammaExponent.ToString(),
                    "",
                    "Gamma Found in File = " + MD.GammaSpecifiedInFile,
                    "",
                    "MetaData:",
                    "  • ISO Speed = " + (MD.ISOSpeed_isValid ? MD.ISOSpeed.ToString() : "N/A"),
                    "  • Exposure Time = " + (MD.ExposureTime_isValid? (MD.ExposureTime > 1.0f ? (MD.ExposureTime + " seconds") : ("1/" + (1.0f / MD.ExposureTime) + " seconds")) : "N/A"),
                    "  • Tv = " + (MD.Tv_isValid ? MD.Tv + " EV" : "N/A"),
                    "  • Av = " + (MD.Av_isValid ? MD.Av + " EV" : "N/A"),
                    "  • F = 1/" + (MD.FNumber_isValid ? MD.FNumber + " stops" : "N/A"),
                    "  • Focal Length = " + (MD.FocalLength_isValid ? MD.FocalLength + " mm" : "N/A"),
                };

            } catch ( Exception _e ) {
                MessageBox.Show( "Error: " + _e.Message );
            }
        }
예제 #57
0
        private void CopyImage(ImageFile imageFile)
        {
            /*
            var packageInfo = PackingInfo.GetPackingInfo(imageFile.OriginalFile.FileInfo.FullName);
            if (packageInfo.IsPackage(PublishTarget.Current))
            {
                string tempFilePath = imageFile.OriginalFile.FileInfo.FullName;
                tempFilePath = tempFilePath.Replace(PathManager.InputPath,
                                                    PathManager.TempPath);

                imageFile.ResultImage.Save(tempFilePath);

                ResourceMapGenerator.AddFileAndTag(imageFile, PublishTarget.Current);
            }
             */
        }
예제 #58
0
        private void GetImagesRecursively(DirectoryInfo dirPath, string prefix)
        {
            var files = SystemTool.GetDirectoryFiles(dirPath);
            foreach (var file in files)
            {
                if (!file.Name.EndsWith(".png"))
                {
                    Logger.LogInfoLine("{0}Only accept png image:{1}", prefix, file);
                    continue;
                }
                var imageFile = new ImageFile(file,true,true);
                //Logger.LogInfoLine("{0}File:\t{1}", prefix, file.FullName.Replace(PathManager.InputImagesPath.FullName, string.Empty));
                bool isPacked = !file.Directory.FullName.Contains(PathManager.InputImageOtherPath.FullName);

                bool isPVREnabled = false;
                if (PublishTarget.Current.IsPVR)
                {
                    isPVREnabled = mPVREnabledDirectoryNames.Any(pvrEnabledDirectoryName => file.Directory.FullName.Contains(pvrEnabledDirectoryName));
                }
                //bool isEffectAnimation = file.Directory.FullName.Contains("EffectAnimation");
                //isPacked &= !isEffectAnimation;
                //bool isOptimzed = !isEffectAnimation;
                if (!PublishTarget.Current.IsPack)
                {
                    isPacked = false;
                }

                bool isOptimzed = PublishTarget.Current.IsOptimzed;
                bool isPOT = PublishTarget.Current.IsPOT;
                bool isSquare = PublishTarget.Current.IsSquare;
                if (isPVREnabled)
                {
                    isPOT = true;
                    isSquare = true;
                }

                ImagePacker.AddImage(imageFile, PublishTarget.Current, isPacked, isOptimzed, isPVREnabled, isPOT, isSquare);
                FilterImage(file);
            }
        }
예제 #59
0
        public void GetAndUpdateImageInfoForProductForStore()
        {
            // Arrange
            var filePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Images\\100001\\") + "02.jpg";
            var imageFile = new ImageFile
            {
                file_content = File.ReadAllBytes(filePath),
                file_mime_type = "image/jpeg",
                file_name = "100001_02"
            };
            var response = Client.AddImageToProduct(productId, imageFile).Result;
            var imageId = response.Result;
            var response1 = Client.GetImageInfoForProduct(productId, imageId).Result;
            var imageInfo = response1.Result;
            var websiteLabel = "Label1";
            imageInfo.label = websiteLabel;
            imageInfo.types = new List<ImageType>
                                  {
                                      ImageType.image,
                                      ImageType.small_image,
                                      ImageType.thumbnail
                                  };
            imageInfo.position = 10;
            var response2 = Client.UpdateImageInfoForProduct(productId, imageId, imageInfo).Result;

            // Act
            imageInfo = new ImageInfo();
            var store2Label = "Label2";
            imageInfo.label = store2Label;
            imageInfo.position = 11;
            imageInfo.types = new List<ImageType>
                                  {
                                      ImageType.image
                                  };
            var response3 = Client.UpdateImageInfoForProductForStore(productId, 2, imageId, imageInfo).Result;
            imageInfo = new ImageInfo();
            var store3Label = "Label3";
            imageInfo.label = store3Label;
            imageInfo.position = 12;
            imageInfo.exclude = true;
            var response4 = Client.UpdateImageInfoForProductForStore(productId, 3, imageId, imageInfo).Result;
            var response5 = Client.GetImageInfoForProductForStore(productId, 2, imageId).Result;
            var response6 = Client.GetImageInfoForProductForStore(productId, 3, imageId).Result;
            var response7 = Client.GetImageInfoForProduct(productId, imageId).Result;

            // Assert
            Assert.IsFalse(response3.HasErrors, response1.ErrorString);
            Assert.IsFalse(response4.HasErrors, response2.ErrorString);
            Assert.IsFalse(response5.HasErrors, response1.ErrorString);
            Assert.IsFalse(response6.HasErrors, response2.ErrorString);
            Assert.IsFalse(response7.HasErrors, response2.ErrorString);

            Assert.AreEqual(websiteLabel, response7.Result.label);
            Assert.AreEqual(store2Label, response5.Result.label);
            Assert.AreEqual(store3Label, response6.Result.label);

            Assert.AreEqual(3, response7.Result.types.Count);
            Assert.AreEqual(1, response5.Result.types.Count);
            Assert.AreEqual(3, response6.Result.types.Count);

            Assert.AreEqual(10, response7.Result.position);
            Assert.AreEqual(11, response5.Result.position);
            Assert.AreEqual(12, response6.Result.position);

            Assert.IsFalse(response7.Result.exclude.Value);
            Assert.IsFalse(response5.Result.exclude.Value);
            Assert.IsTrue(response6.Result.exclude.Value);
        }
예제 #60
0
		/*
		/// <summary>
		/// Bitmaps --> PNG, JPEGs stay as jpegs.
		/// Will delete the incoming file if it needs to do a conversion.
		/// </summary>
		private string ConvertToPngOrJpegIfNotAlready(string incoming)
		{
			string outgoing = incoming;
			//important to dispose of these things, they lock down the file.
			using (var image = Image.FromFile(incoming))
			{
				if (!ImageFormat.Png.Equals(image.PixelFormat) && !ImageFormat.Jpeg.Equals(image.PixelFormat))
				{
					using (var stream = new MemoryStream())
					{
						incoming.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
						var oldCropped = cropped;
						cropped = System.Drawing.Image.FromStream(stream) as Bitmap;
						oldCropped.Dispose();
						Require.That(ImageFormat.Jpeg.Guid == cropped.RawFormat.Guid, "lost jpeg formatting");
					}

					outgoing = Path.GetTempFileName();
					image.Save(outgoing, ImageFormat.Png);
				}
			}
			if (outgoing != incoming)
			{
				try
				{
					File.Delete(incoming);
				}
				catch (Exception e)
				{
					Debug.Fail(e.Message);
					//in release, just keep going
				}
			}
			return outgoing;
		}
		*/

#if !MONO
		private string ConvertToPngOrJpegIfNotAlready(ImageFile wiaImageFile)
		{
			Image acquiredImage;//with my scanner, always a .bmp

			var imageBytes = (byte[])wiaImageFile.FileData.get_BinaryData();
			if (wiaImageFile.FileExtension==".jpg" || wiaImageFile.FileExtension==".png")
			{
				var temp = TempFile.WithExtension(wiaImageFile.FileExtension);
				wiaImageFile.SaveFile(temp.Path);
				return temp.Path;
			}

			using (var stream = new MemoryStream(imageBytes))
			{
				//Ok, so we want to know if we should save a jpeg (photo) or a png (line art).
				//Here, we just chose whichever makes for a the smaller file.
				//Test results
				//                  PNG             JPG
				//B&W Drawing       110k            813k
				//Newspaper photo   1.3M            97k
				//Little doodle     1.7k            11k

				//NB: we do not want to dispose of these, because we will be passing back the path of one
				//(and will manually delete the other)
				TempFile jpeg = TempFile.WithExtension(".jpg");
				TempFile png = TempFile.WithExtension(".png");

				//DOCS: "You must keep the stream open for the lifetime of the Image."(maybe just true for jpegs)
				using (acquiredImage = Image.FromStream(stream))
				{
					acquiredImage.Save(jpeg.Path, ImageFormat.Jpeg);
					acquiredImage.Save(png.Path, ImageFormat.Png);
				}

				//now return the smaller of the two;
				if(new FileInfo(jpeg.Path).Length > new FileInfo(png.Path).Length)
				{
					File.Delete(jpeg.Path);
					return png.Path;
				}
				else
				{
					File.Delete(png.Path);
					return jpeg.Path;
				}
			}
		}