示例#1
0
        public Bitmap(Stream stream, bool useIcm)
        {
            PortableImage dgImage = new PortableImage();

            dgImage.Load(stream);
            SetDGImage(dgImage);
        }
示例#2
0
        public async Task <PortableImage> ResizeImage(PortableImage image, int maxWidthHeight)
        {
            var bitmapImage = (BitmapSource)image.ImageSource;

            int maxWidth = maxWidthHeight;
            int maxHeight = maxWidthHeight;
            int width, height;

            if (bitmapImage.PixelWidth > bitmapImage.PixelHeight)
            {
                width  = maxWidth;
                height = (int)((bitmapImage.PixelHeight / (double)bitmapImage.PixelWidth) * maxWidth);
            }
            else
            {
                height = maxHeight;
                width  = (int)((bitmapImage.PixelWidth / (double)bitmapImage.PixelHeight) * maxHeight);
            }

            return(await ResizeImage(image, width, height));


            //if(!(image.ImageSource is WriteableBitmap))
            //    throw new ArgumentException("image.ImageSource must be of type WriteableBitmap");

            //var resizedImage = ResizeImage((WriteableBitmap) image.ImageSource, maxWidthHeight);
            //var resizedPortableImage = new PortableImage(resizedImage);

            //return resizedPortableImage;
        }
示例#3
0
        public Bitmap(string filename, bool useIcm)
        {
            PortableImage dgImage = new PortableImage();

            dgImage.Load(filename);
            SetDGImage(dgImage);
        }
示例#4
0
 public static Image FromFile
     (string filename, bool useEmbeddedColorManagement)
 {
     var image = new PortableImage();
     image.Load(filename);
     return new Bitmap(image);
 }
        public async Task<PortableImage> ResizeImage(PortableImage image, int maxWidthHeight)
        {
            var bitmapImage = (BitmapSource)image.ImageSource;

            int maxWidth = maxWidthHeight;
            int maxHeight = maxWidthHeight;
            int width, height;

            if (bitmapImage.PixelWidth > bitmapImage.PixelHeight)
            {
                width = maxWidth;
                height = (int)((bitmapImage.PixelHeight / (double)bitmapImage.PixelWidth) * maxWidth);
            }
            else
            {
                height = maxHeight;
                width = (int)((bitmapImage.PixelWidth / (double)bitmapImage.PixelHeight) * maxHeight);
            }

            return await ResizeImage(image, width, height);


            //if(!(image.ImageSource is WriteableBitmap))
            //    throw new ArgumentException("image.ImageSource must be of type WriteableBitmap");

            //var resizedImage = ResizeImage((WriteableBitmap) image.ImageSource, maxWidthHeight);
            //var resizedPortableImage = new PortableImage(resizedImage);

            //return resizedPortableImage;
        }
示例#6
0
 public static Image FromStream
     (Stream stream, bool useEmbeddedColorManagement)
 {
     var image = new PortableImage();
     image.Load(stream);
     return new Bitmap(image);
 }
示例#7
0
文件: Icon.cs 项目: i-e-b/Form8sn
 // Load the icon contents from a stream, and then set the
 // current frame to the first one in the icon image.
 private void Load(Stream stream)
 {
     image = new PortableImage();
     image.Load(stream);
     frame    = image.GetFrame(0);
     frameNum = 0;
 }
示例#8
0
 // This is an internal member and should not be used.
 // Returns a bitmap which is the resized (to newWidth and newHeight) of the first frame.
 public Image Resize(int newWidth, int newHeight)
 {
     Frame frame = dgImage.GetFrame(0);
     Frame newFrame = frame.AdjustImage(0, 0, width, 0, 0, height, 0, 0, newWidth, 0, 0, newHeight);
     var newImage = new PortableImage(newWidth, newHeight, newFrame.PixelFormat);
     newImage.AddFrame(newFrame);
     return new Bitmap(newImage);
 }
示例#9
0
        // Set the dgImage field within this object.
        internal void SetDGImage(PortableImage dgImage)
        {
            flags = (int) dgImage.GetFlags();
#if !ECMA_COMPAT
            switch (dgImage.LoadFormat)
            {
                case PortableImage.Png:
                    rawFormat = ImageFormat.Png;
                    break;
                case PortableImage.Jpeg:
                    rawFormat = ImageFormat.Jpeg;
                    break;
                case PortableImage.Gif:
                    rawFormat = ImageFormat.Gif;
                    break;
                case PortableImage.Tiff:
                    rawFormat = ImageFormat.Tiff;
                    break;
                case PortableImage.Bmp:
                    rawFormat = ImageFormat.Bmp;
                    break;
                case PortableImage.Icon:
                    rawFormat = ImageFormat.Icon;
                    break;
                case PortableImage.Exif:
                    rawFormat = ImageFormat.Exif;
                    break;

                default: // Not loaded from a source?
                    rawFormat = ImageFormat.MemoryBmp;
                    break;
            }

            frameDimensionsList = new Guid [0];
            this.dgImage = dgImage;
            // If we are loading an icon, set the size of the image
            // to the size of the first icon
            if (rawFormat == ImageFormat.Icon)
            {
                width = dgImage.GetFrame(0).Width;
                height = dgImage.GetFrame(0).Height;
            }
            else
            {
                width = dgImage.Width;
                height = dgImage.Height;
            }
#else
				this.dgImage = dgImage;
				width = dgImage.GetFrame(0).Width;
				height = dgImage.GetFrame(0).Height;
#endif
            horizontalResolution = Graphics.DefaultScreenDpi;
            verticalResolution = Graphics.DefaultScreenDpi;
            pixelFormat = (PixelFormat)
                (dgImage.PixelFormat);
        }
示例#10
0
文件: Icon.cs 项目: i-e-b/Form8sn
 private Icon(Icon cloneFrom)
 {
     if (cloneFrom == null)
     {
         throw new ArgumentNullException("cloneFrom");
     }
     image    = (PortableImage)(cloneFrom.image.Clone());
     frameNum = cloneFrom.frameNum;
     frame    = image.GetFrame(frameNum);
 }
示例#11
0
        public static async Task ReplaceImageInStorage(Program project, Look look, PortableImage newImage)
        {
            var path = Path.Combine(project.BasePath, StorageConstants.ProgramLooksPath, look.FileName);

            using (var storage = StorageSystem.GetStorage())
            {
                await storage.SaveImageAsync(path, newImage, true, ImageFormat.Png);
                look.Image = await storage.LoadImageThumbnailAsync(path);
            }
        }
示例#12
0
        public static async Task ReplaceImageInStorage(Program project, Look look, PortableImage newImage)
        {
            var path = Path.Combine(project.BasePath, StorageConstants.ProgramLooksPath, look.FileName);

            using (var storage = StorageSystem.GetStorage())
            {
                await storage.SaveImageAsync(path, newImage, true, ImageFormat.Png);

                look.Image = await storage.LoadImageThumbnailAsync(path);
            }
        }
示例#13
0
        public async Task <PortableImage> LoadImageAsync(string pathToImage)
        {
            if (await FileExistsAsync(pathToImage))
            {
                try
                {
                    //var bitmapImage = new BitmapImage();

                    //var file = await GetFileAsync(pathToImage);
                    //var stream = await file.OpenAsync(FileAccessMode.Read);
                    //bitmapImage.SetSource(stream);

                    //var writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                    //stream.Seek(0);
                    //writeableBitmap.SetSource(stream);
                    //var portableImage = new PortableImage(writeableBitmap);
                    //// TODO: Dispose Stream?
                    //return portableImage;



                    var bitmapImage = new BitmapImage();

                    var file = await GetFileAsync(pathToImage);

                    var stream = await file.OpenAsync(FileAccessMode.Read);

                    var memoryStream = new MemoryStream();
                    stream.GetInputStreamAt(0).AsStreamForRead().CopyTo(memoryStream);
                    stream.Seek(0);
                    bitmapImage.SetSource(stream);

                    // This is sometimes not working, maybe use BitmapDecoder instead?
                    var writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    writeableBitmap.SetSource(memoryStream.AsRandomAccessStream());
                    var portableImage = new PortableImage(writeableBitmap)
                    {
                        Width       = bitmapImage.PixelWidth,
                        Height      = bitmapImage.PixelHeight,
                        EncodedData = memoryStream,
                        ImagePath   = pathToImage
                    };
                    stream.Dispose();
                    return(portableImage);
                }
                catch (Exception exc)
                {
                    return(null);
                }
            }
            return(null);
        }
示例#14
0
文件: Icon.cs 项目: i-e-b/Form8sn
 // Implement the IDisposable interface.
 public void Dispose()
 {
     if (toolkitImage != null)
     {
         toolkitImage.Dispose();
         toolkitImage = null;
     }
     if (image != null)
     {
         image.Dispose();
         image    = null;
         frame    = null;
         frameNum = 0;
     }
 }
示例#15
0
        public async Task <PortableImage> ResizeImage(PortableImage image, int newWidth, int newHeight)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

            var           memoryRandomAccessStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryRandomAccessStream, decoder);

            encoder.BitmapTransform.ScaledHeight = (uint)newHeight;
            encoder.BitmapTransform.ScaledWidth  = (uint)newWidth;


            //var bounds = new BitmapBounds();
            //bounds.Height = 50;
            //bounds.Width = 50;
            //bounds.X = 50;
            //bounds.Y = 50;
            //enc.BitmapTransform.Bounds = bounds;

            try
            {
                await encoder.FlushAsync();
            }
            catch (Exception exc)
            {
                var message = "Error on resizing the image: ";

                if (exc.Message != null)
                {
                    message += exc.Message;
                }

                throw new Exception(message);
            }

            //var writeableBitmap = new WriteableBitmap(newWidth, newHeight);
            //writeableBitmap.SetSourceAsync(memoryRandomAccessStream);

            memoryRandomAccessStream.Seek(0);

            return(new PortableImage
            {
                Width = newWidth,
                Height = newHeight,
                EncodedData = memoryRandomAccessStream.AsStream()
            });
        }
        public async Task<PortableImage> ResizeImage(PortableImage image, int newWidth, int newHeight)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

            var memoryRandomAccessStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryRandomAccessStream, decoder);

            encoder.BitmapTransform.ScaledHeight = (uint)newHeight;
            encoder.BitmapTransform.ScaledWidth = (uint)newWidth;


            //var bounds = new BitmapBounds();
            //bounds.Height = 50;
            //bounds.Width = 50;
            //bounds.X = 50;
            //bounds.Y = 50;
            //enc.BitmapTransform.Bounds = bounds;

            try
            {
                await encoder.FlushAsync();
            }
            catch (Exception exc)
            {
                var message = "Error on resizing the image: ";

                if (exc.Message != null)
                    message += exc.Message;

                throw new Exception(message);
            }

            //var writeableBitmap = new WriteableBitmap(newWidth, newHeight);
            //writeableBitmap.SetSourceAsync(memoryRandomAccessStream);

            memoryRandomAccessStream.Seek(0);

            return new PortableImage
            {
                Width = newWidth,
                Height = newHeight,
                EncodedData = memoryRandomAccessStream.AsStream()
            };
        }
示例#17
0
文件: Frame.cs 项目: i-e-b/Form8sn
 // Constructor.
 internal Frame(PortableImage image, int width, int height, PixelFormat pixelFormat)
 {
     this.image = image;
     this.width = width;
     widthMinusOne = width - 1;
     this.height = height;
     stride = Utils.FormatToStride(pixelFormat, width);
     MaskStride = (((width + 7) / 8) + 3) & ~3;
     this.pixelFormat = pixelFormat;
     Palette = null;
     TransparentPixel = -1;
     HotspotX = 0;
     HotspotY = 0;
     OffsetX = 0;
     OffsetY = 0;
     data = new byte [height * stride];
     mask = null;
     generatedMask = false;
 }
示例#18
0
        public Bitmap(Type type, string resource)
        {
            Stream stream = GetManifestResourceStream(type, resource);

            if (stream == null)
            {
                throw new ArgumentException("Arg_UnknownResource");
            }
            try
            {
                var dgImage = new PortableImage();
                dgImage.Load(stream);
                SetDGImage(dgImage);
            }
            finally
            {
                stream.Close();
            }
        }
示例#19
0
        public static async Task<Look> Save(PortableImage image, string name, ImageDimension dimension, string projectPath)
        {
            using (var storage = StorageSystem.GetStorage())
            {
                var imagePath = Path.Combine(projectPath, StorageConstants.ProgramLooksPath);
                if (!await storage.DirectoryExistsAsync(imagePath))
                    await storage.CreateDirectoryAsync(imagePath);
            }

            var resizedImage = await ServiceLocator.ImageResizeService.ResizeImage(image, dimension.Width, dimension.Height);
            var look = new Look(name);
            var absoluteFileName = Path.Combine(projectPath, StorageConstants.ProgramLooksPath, look.FileName);

            await resizedImage.WriteAsPng(absoluteFileName);

            //look.Image = resizedImage;

            return look;
        }
示例#20
0
文件: Frame.cs 项目: i-e-b/Form8sn
        private Frame(PortableImage newImage, Frame frame, int newWidth, int newHeight, PixelFormat format, bool cloneData)
        {
            // Clone from the other frame.
            image = newImage;
            width = newWidth;
            widthMinusOne = newWidth - 1;
            height = newHeight;
            pixelFormat = format;
            stride = Utils.FormatToStride(pixelFormat, width);
            MaskStride = (((width + 7) / 8) + 3) & ~3;
            generatedMask = false;
            if (frame.Palette != null)
            {
                if (newImage != null && frame.Palette == frame.image.Palette)
                {
                    // The palette is a copy of the image's.
                    Palette = newImage.Palette;
                }
                else if (cloneData)
                {
                    // The palette is specific to this frame.
                    Palette = (int[]) (frame.Palette.Clone());
                }
            }

            TransparentPixel = frame.TransparentPixel;
            HotspotX = frame.HotspotX;
            HotspotY = frame.HotspotY;
            OffsetX = frame.OffsetX;
            OffsetY = frame.OffsetY;
            if (cloneData & frame.data != null)
            {
                data = (byte[]) (frame.data.Clone());
            }

            if (cloneData & frame.mask != null)
            {
                mask = (byte[]) (frame.mask.Clone());
                generatedMask = frame.generatedMask;
            }
        }
示例#21
0
        public static async Task <Look> Save(PortableImage image, string name, ImageDimension dimension, string projectPath)
        {
            using (var storage = StorageSystem.GetStorage())
            {
                var imagePath = Path.Combine(projectPath, StorageConstants.ProgramLooksPath);
                if (!await storage.DirectoryExistsAsync(imagePath))
                {
                    await storage.CreateDirectoryAsync(imagePath);
                }
            }

            var resizedImage = await ServiceLocator.ImageResizeService.ResizeImage(image, dimension.Width, dimension.Height);

            var look             = new Look(name);
            var absoluteFileName = Path.Combine(projectPath, StorageConstants.ProgramLooksPath, look.FileName);

            await resizedImage.WriteAsPng(absoluteFileName);

            //look.Image = resizedImage;

            return(look);
        }
        public async Task SaveImageAsync(string path, PortableImage image, bool deleteExisting, ImageFormat format)
        {
            var withoutExtension = Path.GetFileNameWithoutExtension(path);
            var thumbnailPath = string.Format("{0}{1}", withoutExtension, StorageConstants.ImageThumbnailExtension);

            if (deleteExisting)
            {
                await DeleteFileAsync(path);
                await DeleteFileAsync(thumbnailPath);
            }

            Stream stream = null;

            try
            {
                stream = await OpenFileAsync(path, StorageFileMode.CreateNew, StorageFileAccess.Write);

                switch (format)
                {
                    case ImageFormat.Png:
                        if (image.EncodedData != null)
                        {
                            await image.EncodedData.CopyToAsync(stream);
                        }
                        else
                        {
                            throw new NotImplementedException("This code does not work properly");

                            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

                            var memoryStream = new InMemoryRandomAccessStream();
                            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryStream, decoder);

                            try
                            {
                                await encoder.FlushAsync();
                            }
                            catch (Exception exc)
                            {
                                var message = "Error on writing the image: ";

                                if (exc.Message != null)
                                    message += exc.Message;

                                throw new Exception(message);
                            }

                            //await ((WriteableBitmap)image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                            //await PNGWriter.WritePNG((WriteableBitmap)image.ImageSource, stream, 95);
                        }

                        //throw new NotImplementedException();
                        //
                        break;
                    case ImageFormat.Jpg:
                        //await ((WriteableBitmap) image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                        //((WriteableBitmap)image.ImageSource).SaveJpeg(stream, image.Width, image.Height, 0, 95);
                        throw new NotImplementedException();

                        break;
                    default:
                        throw new ArgumentOutOfRangeException("format");
                }
            }
            catch (Exception exc)
            {
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Dispose();
                }
            }
        }
示例#23
0
        public async void RecievedFiles(IEnumerable <object> files)
        {
            var fileArray = files as object[] ?? files.ToArray();

            if (fileArray.Length == 0)
            {
                ServiceLocator.DispatcherService.RunOnMainThread(() =>
                                                                 ServiceLocator.NavigationService.NavigateTo <NewLookSourceSelectionViewModel>());
            }
            StorageFile file = (StorageFile)fileArray[0];

            var fileStream = await file.OpenReadAsync();

            var memoryStream = new MemoryStream();

            fileStream.AsStreamForRead().CopyTo(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            BitmapImage imagetobind = new BitmapImage();
            await imagetobind.SetSourceAsync(memoryStream.AsRandomAccessStream());

            WriteableBitmap writeableBitmap = new WriteableBitmap(imagetobind.PixelWidth, imagetobind.PixelHeight);
            await writeableBitmap.FromStream(memoryStream.AsRandomAccessStream());

            memoryStream.Seek(0, SeekOrigin.Begin);
            PortableImage portableImage = new PortableImage(writeableBitmap)
            {
                Width       = writeableBitmap.PixelWidth,
                Height      = writeableBitmap.PixelHeight,
                EncodedData = memoryStream
            };

            if (_lookToEdit == null)
            {
                if (portableImage != null) // TODO: check if image is ok
                {
                    var message = new GenericMessage <PortableImage>(portableImage);
                    Messenger.Default.Send(message, ViewModelMessagingToken.LookImageListener);

                    ServiceLocator.DispatcherService.RunOnMainThread(() =>
                                                                     ServiceLocator.NavigationService.NavigateTo <LookNameChooserViewModel>());
                }
                else
                {
                    ServiceLocator.NotifictionService.ShowMessageBox(AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatHeader"),
                                                                     AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatText"), delegate { /* no action */ }, MessageBoxOptions.Ok);
                }
            }
            else
            {
                using (var storage = StorageSystem.GetStorage())
                {
                    var filePath = Path.Combine(_program.BasePath,
                                                StorageConstants.ProgramLooksPath, _lookToEdit.FileName);

                    await storage.DeleteImageAsync(filePath);

                    var lookFileStream = await storage.OpenFileAsync(filePath,
                                                                     StorageFileMode.Create, StorageFileAccess.Write);

                    await(await file.OpenReadAsync()).AsStream().CopyToAsync(lookFileStream);

                    lookFileStream.Dispose();

                    await storage.TryCreateThumbnailAsync(filePath);

                    _lookToEdit.Image = await storage.LoadImageThumbnailAsync(filePath);
                }

                _lookToEdit = null;
            }
        }
示例#24
0
 public IToolkitImage CreateImage(PortableImage image, int frame)
 {
     image.SetActiveFrame(frame);
     return(image);
 }
        private async Task UpdateLocalPrograms()
        {
            if (IsInDesignMode) return;

            if (_localPrograms == null)
            {
                _localPrograms = new ObservableCollection<LocalProgramHeader>();
            }

            //_localPrograms.Clear();

            using (var storage = StorageSystem.GetStorage())
            {
                var programNames = await storage.GetDirectoryNamesAsync(StorageConstants.ProgramsPath);

                //var programs = new List<ProgramDummyHeader>();

                var programsToRemove = new List<LocalProgramHeader>();

                foreach (var header in _localPrograms)
                {
                    var found = false;
                    foreach (string programName in programNames)
                        if (header.ProjectName == programName)
                            found = true;

                    if (!found)
                        programsToRemove.Add(header);
                }

                //foreach (var header in _localProjects)
                //{
                //    if (header.ProjectName == CurrentProgram.ProjectDummyHeader.ProjectName)
                //        programsToRemove.Add(header);
                //}


                foreach (var program in programsToRemove)
                {
                    _localPrograms.Remove(program);
                }



                //var programsToAdd = new List<LocalProgramHeader>();

                foreach (string programName in programNames)
                {
                    LocalProgramHeader header = null;

                    foreach (var h in _localPrograms)
                    {
                        if (h.ProjectName == programName)
                            header = h;
                    }

                    if (header == null)
                    {
                        var manualScreenshotPath = Path.Combine(
                            StorageConstants.ProgramsPath, programName, StorageConstants.ProgramManualScreenshotPath);
                        var automaticProjectScreenshotPath = Path.Combine(
                            StorageConstants.ProgramsPath, programName, StorageConstants.ProgramAutomaticScreenshotPath);

                        var codePath = Path.Combine(StorageConstants.ProgramsPath,
                            programName, StorageConstants.ProgramCodePath);

                        var programScreenshot = new PortableImage();
                        programScreenshot.LoadAsync(manualScreenshotPath, automaticProjectScreenshotPath, false);

                        var isLoaded = !await storage.FileExistsAsync(codePath);

                        var programHeader = new LocalProgramHeader
                        {
                            ProjectName = programName,
                            Screenshot = programScreenshot,
                            IsLoading = isLoaded
                        };

                        _localPrograms.Insert(0, programHeader);
                    }
                    else if (header.IsLoading)
                    {
                        var codePath = Path.Combine(StorageConstants.ProgramsPath,
                            programName, StorageConstants.ProgramCodePath);
                        var isLoaded = !await storage.FileExistsAsync(codePath);
                        header.IsLoading = isLoaded;
                    }
                }

                //programsToAdd.Sort();


                //foreach (var program in programsToAdd)
                //{
                //    _localPrograms.Insert(0, program);
                //}
            }
        }
        public async void RecievedFiles(IEnumerable<object> files)
        {
            var fileArray = files as object[] ?? files.ToArray();

            if (fileArray.Length == 0)
            {
                ServiceLocator.DispatcherService.RunOnMainThread(() =>
                    ServiceLocator.NavigationService.NavigateTo<NewLookSourceSelectionViewModel>());
            }
            StorageFile file = (StorageFile)fileArray[0];

            var fileStream = await file.OpenReadAsync();
            var memoryStream = new MemoryStream();
            fileStream.AsStreamForRead().CopyTo(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            BitmapImage imagetobind = new BitmapImage();
            await imagetobind.SetSourceAsync(memoryStream.AsRandomAccessStream());

            WriteableBitmap writeableBitmap = new WriteableBitmap(imagetobind.PixelWidth, imagetobind.PixelHeight);
            await writeableBitmap.FromStream(memoryStream.AsRandomAccessStream());
            memoryStream.Seek(0, SeekOrigin.Begin);
            PortableImage portableImage = new PortableImage(writeableBitmap)
            {
                Width = writeableBitmap.PixelWidth,
                Height = writeableBitmap.PixelHeight,
                EncodedData = memoryStream
            };

            if (_lookToEdit == null)
            {
                if (portableImage != null) // TODO: check if image is ok
                {
                    var message = new GenericMessage<PortableImage>(portableImage);
                    Messenger.Default.Send(message, ViewModelMessagingToken.LookImageListener);

                    ServiceLocator.DispatcherService.RunOnMainThread(() =>
                        ServiceLocator.NavigationService.NavigateTo<LookNameChooserViewModel>());
                }
                else
                {
                    ServiceLocator.NotifictionService.ShowMessageBox(AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatHeader"),
                        AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatText"), delegate { /* no action */ }, MessageBoxOptions.Ok);
                }
            }
            else
            {
                using (var storage = StorageSystem.GetStorage())
                {
                    var filePath = Path.Combine(_program.BasePath,
                        StorageConstants.ProgramLooksPath, _lookToEdit.FileName);

                    await storage.DeleteImageAsync(filePath);

                    var lookFileStream = await storage.OpenFileAsync(filePath,
                        StorageFileMode.Create, StorageFileAccess.Write);

                    await (await file.OpenReadAsync()).AsStream().CopyToAsync(lookFileStream);

                    lookFileStream.Dispose();

                    await storage.TryCreateThumbnailAsync(filePath);

                    _lookToEdit.Image = await storage.LoadImageThumbnailAsync(filePath);
                }

                _lookToEdit = null;
            }
        }
示例#27
0
        public void ShowToastNotification(string title, string message,
                                          ToastDisplayDuration displayDuration, ToastTag tag = ToastTag.Default, PortableImage image = null, bool vibrate = false)
        {
            var duration = ToastDuration.Short;

            switch (displayDuration)
            {
            case ToastDisplayDuration.Short:
                duration = ToastDuration.Short;
                break;

            case ToastDisplayDuration.Long:
                duration = ToastDuration.Long;
                break;

            default:
                throw new ArgumentOutOfRangeException("timeTillHide");
            }

            IToastText02 templateContent = ToastContentFactory.CreateToastText02();

            //templateContent.TextHeading.Text = title;
            templateContent.TextBodyWrap.Text = message;
            templateContent.Duration          = duration;

            templateContent.Audio.Content = ToastAudioContent.Silent;


            var toast = templateContent.CreateNotification();

            toast.Tag        = tag.ToString();
            toast.Activated += ToastOnActivated;
            toast.Dismissed += ToastOnDismissed;
            toast.Failed    += ToastOnFailed;

            if (vibrate)
            {
                VibrationDevice.GetDefault().Vibrate(TimeSpan.FromSeconds(0.5));
            }

            ServiceLocator.DispatcherService.RunOnMainThread(() =>
                                                             ToastNotificationManager.CreateToastNotifier().Show(toast));
        }
        private async Task UpdateLocalPrograms()
        {
            if (IsInDesignMode)
            {
                return;
            }

            if (_localPrograms == null)
            {
                _localPrograms = new ObservableCollection <LocalProgramHeader>();
            }

            //_localPrograms.Clear();

            using (var storage = StorageSystem.GetStorage())
            {
                var programNames = await storage.GetDirectoryNamesAsync(StorageConstants.ProgramsPath);

                //var programs = new List<ProgramDummyHeader>();

                var programsToRemove = new List <LocalProgramHeader>();

                foreach (var header in _localPrograms)
                {
                    var found = false;
                    foreach (string programName in programNames)
                    {
                        if (header.ProjectName == programName)
                        {
                            found = true;
                        }
                    }

                    if (!found)
                    {
                        programsToRemove.Add(header);
                    }
                }

                //foreach (var header in _localProjects)
                //{
                //    if (header.ProjectName == CurrentProgram.ProjectDummyHeader.ProjectName)
                //        programsToRemove.Add(header);
                //}


                foreach (var program in programsToRemove)
                {
                    _localPrograms.Remove(program);
                }



                //var programsToAdd = new List<LocalProgramHeader>();

                foreach (string programName in programNames)
                {
                    LocalProgramHeader header = null;

                    foreach (var h in _localPrograms)
                    {
                        if (h.ProjectName == programName)
                        {
                            header = h;
                        }
                    }

                    if (header == null)
                    {
                        var manualScreenshotPath = Path.Combine(
                            StorageConstants.ProgramsPath, programName, StorageConstants.ProgramManualScreenshotPath);
                        var automaticProjectScreenshotPath = Path.Combine(
                            StorageConstants.ProgramsPath, programName, StorageConstants.ProgramAutomaticScreenshotPath);

                        var codePath = Path.Combine(StorageConstants.ProgramsPath,
                                                    programName, StorageConstants.ProgramCodePath);

                        var programScreenshot = new PortableImage();
                        programScreenshot.LoadAsync(manualScreenshotPath, automaticProjectScreenshotPath, false);

                        var isLoaded = !await storage.FileExistsAsync(codePath);

                        var programHeader = new LocalProgramHeader
                        {
                            ProjectName = programName,
                            Screenshot  = programScreenshot,
                            IsLoading   = isLoaded
                        };

                        _localPrograms.Insert(0, programHeader);
                    }
                    else if (header.IsLoading)
                    {
                        var codePath = Path.Combine(StorageConstants.ProgramsPath,
                                                    programName, StorageConstants.ProgramCodePath);
                        var isLoaded = !await storage.FileExistsAsync(codePath);

                        header.IsLoading = isLoaded;
                    }
                }

                //programsToAdd.Sort();


                //foreach (var program in programsToAdd)
                //{
                //    _localPrograms.Insert(0, program);
                //}
            }
        }
示例#29
0
 internal Bitmap(PortableImage image) : base(image)
 {
 }
示例#30
0
文件: Frame.cs 项目: i-e-b/Form8sn
 internal void NewImage(PortableImage newImage)
 {
     image = newImage;
 }
        public async Task<PortableImage> LoadImageAsync(string pathToImage)
        {
            if (await FileExistsAsync(pathToImage))
            {
                try
                {
                    //var bitmapImage = new BitmapImage();

                    //var file = await GetFileAsync(pathToImage);
                    //var stream = await file.OpenAsync(FileAccessMode.Read);
                    //bitmapImage.SetSource(stream);

                    //var writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                    //stream.Seek(0);
                    //writeableBitmap.SetSource(stream);
                    //var portableImage = new PortableImage(writeableBitmap);
                    //// TODO: Dispose Stream?
                    //return portableImage;




                    var bitmapImage = new BitmapImage();

                    var file = await GetFileAsync(pathToImage);
                    var stream = await file.OpenAsync(FileAccessMode.Read);
                    var memoryStream = new MemoryStream();
                    stream.GetInputStreamAt(0).AsStreamForRead().CopyTo(memoryStream);
                    stream.Seek(0);
                    bitmapImage.SetSource(stream);

                    // This is sometimes not working, maybe use BitmapDecoder instead?
                    var writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    writeableBitmap.SetSource(memoryStream.AsRandomAccessStream());
                    var portableImage = new PortableImage(writeableBitmap)
                    {
                        Width = bitmapImage.PixelWidth,
                        Height = bitmapImage.PixelHeight,
                        EncodedData = memoryStream,
                        ImagePath = pathToImage
                    };
                    stream.Dispose();
                    return portableImage;
                }
                catch (Exception exc)
                {
                    return null;
                }
            }
            return null;
        }
示例#32
0
 internal Image(PortableImage dgImage)
 {
     SetDGImage(dgImage);
 }
示例#33
0
        public async Task SaveImageAsync(string path, PortableImage image, bool deleteExisting, ImageFormat format)
        {
            var withoutExtension = Path.GetFileNameWithoutExtension(path);
            var thumbnailPath    = string.Format("{0}{1}", withoutExtension, StorageConstants.ImageThumbnailExtension);

            if (deleteExisting)
            {
                await DeleteFileAsync(path);
                await DeleteFileAsync(thumbnailPath);
            }

            Stream stream = null;

            try
            {
                stream = await OpenFileAsync(path, StorageFileMode.CreateNew, StorageFileAccess.Write);

                switch (format)
                {
                case ImageFormat.Png:
                    if (image.EncodedData != null)
                    {
                        await image.EncodedData.CopyToAsync(stream);
                    }
                    else
                    {
                        throw new NotImplementedException("This code does not work properly");

                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

                        var           memoryStream = new InMemoryRandomAccessStream();
                        BitmapEncoder encoder      = await BitmapEncoder.CreateForTranscodingAsync(memoryStream, decoder);

                        try
                        {
                            await encoder.FlushAsync();
                        }
                        catch (Exception exc)
                        {
                            var message = "Error on writing the image: ";

                            if (exc.Message != null)
                            {
                                message += exc.Message;
                            }

                            throw new Exception(message);
                        }

                        //await ((WriteableBitmap)image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                        //await PNGWriter.WritePNG((WriteableBitmap)image.ImageSource, stream, 95);
                    }

                    //throw new NotImplementedException();
                    //
                    break;

                case ImageFormat.Jpg:
                    //await ((WriteableBitmap) image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                    //((WriteableBitmap)image.ImageSource).SaveJpeg(stream, image.Width, image.Height, 0, 95);
                    throw new NotImplementedException();

                    break;

                default:
                    throw new ArgumentOutOfRangeException("format");
                }
            }
            catch (Exception exc)
            {
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Dispose();
                }
            }
        }
示例#34
0
文件: J2kImage.cs 项目: cureos/csj2k
        public static PortableImage FromStream(Stream stream, ParameterList parameters = null)
        {
            RandomAccessIO in_stream = new ISRandomAccessIO(stream);

            // Initialize default parameters
            ParameterList defpl = GetDefaultDecoderParameterList(decoder_pinfo);

            // Create parameter list using defaults
            ParameterList pl = parameters ?? new ParameterList(defpl);

            // **** File Format ****
            // If the codestream is wrapped in the jp2 fileformat, Read the
            // file format wrapper
            FileFormatReader ff = new FileFormatReader(in_stream);
            ff.readFileFormat();
            if (ff.JP2FFUsed)
            {
                in_stream.seek(ff.FirstCodeStreamPos);
            }

            // +----------------------------+
            // | Instantiate decoding chain |
            // +----------------------------+

            // **** Header decoder ****
            // Instantiate header decoder and read main header
            HeaderInfo hi = new HeaderInfo();
            HeaderDecoder hd;
            try
            {
                hd = new HeaderDecoder(in_stream, pl, hi);
            }
            catch (EndOfStreamException e)
            {
                throw new InvalidOperationException("Codestream too short or bad header, unable to decode.", e);
            }

            int nCompCod = hd.NumComps;
            int nTiles = hi.sizValue.NumTiles;
            DecoderSpecs decSpec = hd.DecoderSpecs;

            // Get demixed bitdepths
            int[] depth = new int[nCompCod];
            for (int i = 0; i < nCompCod; i++)
            {
                depth[i] = hd.getOriginalBitDepth(i);
            }

            // **** Bit stream reader ****
            BitstreamReaderAgent breader;
            try
            {
                breader = BitstreamReaderAgent.createInstance(in_stream, hd, pl, decSpec, false, hi);
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("Error while reading bit stream header or parsing packets.", e);
            }
            catch (ArgumentException e)
            {
                throw new InvalidOperationException("Cannot instantiate bit stream reader.", e);
            }

            // **** Entropy decoder ****
            EntropyDecoder entdec;
            try
            {
                entdec = hd.createEntropyDecoder(breader, pl);
            }
            catch (ArgumentException e)
            {
                throw new InvalidOperationException("Cannot instantiate entropy decoder.", e);
            }

            // **** ROI de-scaler ****
            ROIDeScaler roids;
            try
            {
                roids = hd.createROIDeScaler(entdec, pl, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new InvalidOperationException("Cannot instantiate roi de-scaler.", e);
            }

            // **** Dequantizer ****
            Dequantizer deq;
            try
            {
                deq = hd.createDequantizer(roids, depth, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new InvalidOperationException("Cannot instantiate dequantizer.", e);
            }

            // **** Inverse wavelet transform ***
            InverseWT invWT;
            try
            {
                // full page inverse wavelet transform
                invWT = InverseWT.createInstance(deq, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new InvalidOperationException("Cannot instantiate inverse wavelet transform.", e);
            }

            int res = breader.ImgRes;
            invWT.ImgResLevel = res;

            // **** Data converter **** (after inverse transform module)
            ImgDataConverter converter = new ImgDataConverter(invWT, 0);

            // **** Inverse component transformation ****
            InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl);

            // **** Color space mapping ****
            BlkImgDataSrc color;
            if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off"))
            {
                try
                {
                    ColorSpace csMap = new ColorSpace(in_stream, hd, pl);
                    BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap);
                    BlkImgDataSrc resampled = hd.createResampler(channels, csMap);
                    BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap);
                    color = hd.createColorSpaceMapper(palettized, csMap);
                }
                catch (ArgumentException e)
                {
                    throw new InvalidOperationException("Could not instantiate ICC profiler.", e);
                }
                catch (ColorSpaceException e)
                {
                    throw new InvalidOperationException("Error processing ColorSpace information.", e);
                }
            }
            else
            {
                // Skip colorspace mapping
                color = ictransf;
            }

            // This is the last image in the decoding chain and should be
            // assigned by the last transformation:
            BlkImgDataSrc decodedImage = color;
            if (color == null)
            {
                decodedImage = ictransf;
            }
            int numComps = decodedImage.NumComps;

            int bytesPerPixel = (numComps == 4 ? 4 : 3);

            // **** Copy to Bitmap ****
            var dst = new PortableImage(decodedImage.ImgWidth, decodedImage.ImgHeight, numComps);

            Coord numTiles = decodedImage.getNumTiles(null);

            int tIdx = 0;

            for (int y = 0; y < numTiles.y; y++)
            {
                // Loop on horizontal tiles
                for (int x = 0; x < numTiles.x; x++, tIdx++)
                {
                    decodedImage.setTile(x, y);

                    int height = decodedImage.getTileCompHeight(tIdx, 0);
                    int width = decodedImage.getTileCompWidth(tIdx, 0);

                    int tOffx = decodedImage.getCompULX(0)
                                - (int)Math.Ceiling(decodedImage.ImgULX / (double)decodedImage.getCompSubsX(0));

                    int tOffy = decodedImage.getCompULY(0)
                                - (int)Math.Ceiling(decodedImage.ImgULY / (double)decodedImage.getCompSubsY(0));

                    DataBlkInt[] db = new DataBlkInt[numComps];
                    int[] ls = new int[numComps];
                    int[] mv = new int[numComps];
                    int[] fb = new int[numComps];
                    for (int i = 0; i < numComps; i++)
                    {
                        db[i] = new DataBlkInt();
                        ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1);
                        mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1;
                        fb[i] = decodedImage.getFixedPoint(0);
                    }
                    for (int l = 0; l < height; l++)
                    {
                        for (int i = numComps - 1; i >= 0; i--)
                        {
                            db[i].ulx = 0;
                            db[i].uly = l;
                            db[i].w = width;
                            db[i].h = 1;
                            decodedImage.getInternCompData(db[i], i);
                        }
                        int[] k = new int[numComps];
                        for (int i = numComps - 1; i >= 0; i--) k[i] = db[i].offset + width - 1;

                        byte[] rowvalues = new byte[width * bytesPerPixel];

                        for (int i = width - 1; i >= 0; i--)
                        {
                            int[] tmp = new int[numComps];
                            for (int j = numComps - 1; j >= 0; j--)
                            {
                                tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j];
                                tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]);

                                if (decodedImage.getNomRangeBits(j) != 8)
                                    tmp[j] =
                                        (int)
                                        Math.Round(
                                            ((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j)))
                                            * 255D);

                            }
                            int offset = i * bytesPerPixel;
                            switch (numComps)
                            {
                                case 1:
                                    rowvalues[offset + 0] = (byte)tmp[0];
                                    rowvalues[offset + 1] = (byte)tmp[0];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 3:
                                    rowvalues[offset + 0] = (byte)tmp[2];
                                    rowvalues[offset + 1] = (byte)tmp[1];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 4:
                                    rowvalues[offset + 0] = (byte)tmp[3];
                                    rowvalues[offset + 1] = (byte)tmp[2];
                                    rowvalues[offset + 2] = (byte)tmp[1];
                                    rowvalues[offset + 3] = (byte)tmp[0];
                                    break;
                            }
                        }

                        dst.FillRow(tOffx, tOffy + l, width, rowvalues);
                    }
                }
            }

            return dst;
        }
示例#35
0
 /// <summary>
 /// Create a dummy graphics that is attached to no drawing surface
 /// </summary>
 /// <param name="parent"></param>
 public PortableGraphics(IToolkit parent)
 {
     Target  = new PortableImage();
     Toolkit = parent;
     DpiX    = DpiY = 96.0f; // default Windows-like value
 }
        public async Task <CheckProgramResult> CheckProgram(string pathToProgramDirectory)
        {
            var pathToProgramCodeFile = Path.Combine(pathToProgramDirectory, StorageConstants.ProgramCodePath);

            XmlProgram    convertedProgram  = null;
            var           checkResult       = new CheckProgramResult();
            PortableImage programScreenshot = null;
            string        programName       = null;
            string        programCode       = null;

            using (var storage = StorageSystem.GetStorage())
            {
                programScreenshot =
                    await storage.LoadImageAsync(Path.Combine(
                                                     pathToProgramDirectory,
                                                     StorageConstants.ProgramManualScreenshotPath)) ??
                    await storage.LoadImageAsync(Path.Combine(
                                                     pathToProgramDirectory,
                                                     StorageConstants.ProgramAutomaticScreenshotPath));

                if (!await storage.FileExistsAsync(pathToProgramCodeFile))
                {
                    checkResult.State = ProgramState.FilesMissing;
                    return(checkResult);
                }
                programCode = await storage.ReadTextFileAsync(pathToProgramCodeFile);
            }

            var converterResult = await CatrobatVersionConverter.
                                  ConvertToXmlVersion(programCode, XmlConstants.TargetIDEVersion);

            if (converterResult.Error != CatrobatVersionConverter.VersionConverterStatus.NoError)
            {
                switch (converterResult.Error)
                {
                case CatrobatVersionConverter.VersionConverterStatus.VersionTooNew:
                    checkResult.State = ProgramState.VersionTooNew;
                    break;

                case CatrobatVersionConverter.VersionConverterStatus.VersionTooOld:
                    checkResult.State = ProgramState.VersionTooOld;
                    break;

                default:
                    checkResult.State = ProgramState.Damaged;
                    break;
                }
                return(checkResult);
            }

            try
            {
                convertedProgram = new XmlProgram(converterResult.Xml);
                programName      = convertedProgram.ProgramHeader.ProgramName;
            }
            catch (Exception)
            {
                checkResult.State         = ProgramState.Damaged;
                checkResult.ProgramHeader = null;
                checkResult.Program       = null;
                return(checkResult);
            }

            try
            {
                ProgramConverter programConverter = new ProgramConverter();
                checkResult.Program = programConverter.Convert(convertedProgram);
                NativeWrapper.SetProject(convertedProgram);
            }
            catch (Exception)
            {
                checkResult.State         = ProgramState.ErrorInThisApp;
                checkResult.ProgramHeader = null;
                checkResult.Program       = null;
                return(checkResult);
            }

            if (programName == null)
            {
                programName = XmlProgramHelper.GetProgramName(converterResult.Xml);
            }

            checkResult.ProgramHeader = new LocalProgramHeader
            {
                Screenshot  = programScreenshot,
                ProjectName = programName,
            };

            checkResult.State = ProgramState.Valid;
            return(checkResult);
        }
示例#37
0
文件: Frame.cs 项目: i-e-b/Form8sn
 // Clone this frame into a new image.
 internal Frame CloneFrame(PortableImage newImage)
 {
     return new Frame(newImage, this, width, height, pixelFormat, true);
 }