Beispiel #1
0
        /// <summary>
        /// Export the map to an image.
        /// </summary>
        public Image Export()
        {
            // Create a Bitmap and draw the DataGridView on it.
            int width;
            int height;

            if (ProcessUtilities.CurrentOS.IsWindows)
            {
                // Give the browser half a second to run all its scripts
                // It would be better if we could tap into the browser's Javascript engine
                // and see whether loading of the map was complete, but my attempts to do
                // so were not entirely successful.
                Stopwatch watch = new Stopwatch();
                watch.Start();
                while (watch.ElapsedMilliseconds < 500)
                {
                    Gtk.Application.RunIteration();
                }
            }
            Gdk.Window gridWindow = MainWidget.GdkWindow;
            gridWindow.GetSize(out width, out height);
            Gdk.Pixbuf   screenshot = Gdk.Pixbuf.FromDrawable(gridWindow, gridWindow.Colormap, 0, 0, 0, 0, width, height);
            byte[]       buffer     = screenshot.SaveToBuffer("png");
            MemoryStream stream     = new MemoryStream(buffer);

            System.Drawing.Bitmap bitmap = new Bitmap(stream);
            return(bitmap);
        }
Beispiel #2
0
        /// <summary>Export the view to the image</summary>
        public System.Drawing.Image Export()
        {
            var window = new OffscreenWindow();

            window.Add(MainWidget);

            // Choose a good size for the image (which is square).
            int maxX    = (int)nodes.Max(n => n.Location.X);
            int maxY    = (int)nodes.Max(n => n.Location.Y);
            int maxSize = nodes.Max(n => n.Width);
            int size    = Math.Max(maxX, maxY) + maxSize;

            MainWidget.WidthRequest  = size;
            MainWidget.HeightRequest = size;
            window.ShowAll();
            while (GLib.MainContext.Iteration())
            {
                ;
            }

            Gdk.Pixbuf screenshot = window.Pixbuf;
            byte[]     buffer     = screenshot.SaveToBuffer("png");
            window.Dispose();
            using (MemoryStream stream = new MemoryStream(buffer))
            {
                System.Drawing.Bitmap bitmap = new Bitmap(stream);
                return(bitmap);
            }
        }
        public DataCollection Serialize(ITypeSerializer handler)
        {
            DataCollection dc = handler.Serialize(this);

            dc.Extract("filters");
            dc.Extract("icon");

            DataItem filtersItem = new DataItem();

            filtersItem.Name = "filters";
            dc.Add(filtersItem);

            foreach (ToolboxItemFilterAttribute tbfa in itemFilters)
            {
                DataItem item = new DataItem();
                item.Name = "filter";
                item.ItemData.Add(new DataValue("string", tbfa.FilterString));
                item.ItemData.Add(new DataValue("type", System.Enum.GetName(typeof(ToolboxItemFilterType), tbfa.FilterType)));
                filtersItem.ItemData.Add(item);
            }

            if (icon != null)
            {
                DataItem item = new DataItem();
                item.Name = "icon";
                dc.Add(item);
                string iconString = Convert.ToBase64String(icon.SaveToBuffer("png"));
                item.ItemData.Add(new DataValue("enc", iconString));
            }

            return(dc);
        }
Beispiel #4
0
        protected override void AddTrackToDevice(DatabaseTrackInfo track, SafeUri fromUri)
        {
            if (track.PrimarySourceId == DbId)
            {
                return;
            }

            lock (mtp_device) {
                Track mtp_track = TrackInfoToMtpTrack(track, fromUri);
                bool  video     = track.HasAttribute(TrackMediaAttributes.VideoStream);
                mtp_device.UploadTrack(fromUri.LocalPath, mtp_track, GetFolderForTrack(track), OnUploadProgress);

                // Add/update album art
                if (!video)
                {
                    string key = MakeAlbumKey(track.AlbumArtist, track.AlbumTitle);
                    if (!album_cache.ContainsKey(key))
                    {
                        Album album = new Album(mtp_device, track.AlbumTitle, track.AlbumArtist, track.Genre, track.Composer);
                        album.AddTrack(mtp_track);

                        if (supports_jpegs && can_sync_albumart)
                        {
                            try {
                                Gdk.Pixbuf pic = ServiceManager.Get <Banshee.Collection.Gui.ArtworkManager> ().LookupScalePixbuf(
                                    track.ArtworkId, thumb_width
                                    );
                                if (pic != null)
                                {
                                    byte [] bytes = pic.SaveToBuffer("jpeg");
                                    album.Save(bytes, (uint)pic.Width, (uint)pic.Height);
                                    Banshee.Collection.Gui.ArtworkManager.DisposePixbuf(pic);
                                }
                                album_cache[key] = album;
                            } catch (Exception e) {
                                Log.Debug("Failed to create MTP Album", e.Message);
                            }
                        }
                        else
                        {
                            album.Save();
                            album_cache[key] = album;
                        }
                    }
                    else
                    {
                        Album album = album_cache[key];
                        album.AddTrack(mtp_track);
                        album.Save();
                    }
                }

                MtpTrackInfo new_track = new MtpTrackInfo(mtp_device, mtp_track);
                new_track.PrimarySource = this;
                new_track.Save(false);
                track_map[new_track.TrackId] = mtp_track;
            }
        }
 /// <summary>Get the image from clipboard</summary>
 private static System.Drawing.Image GtkGetImage()
 {
     using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false)))
     {
         Gdk.Pixbuf    buff = cb.WaitForImage();
         TypeConverter tc   = TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
         return((System.Drawing.Image)tc.ConvertFrom(buff.SaveToBuffer("png")));
     }
 }
 protected override void SendImage(Photo photo, Stream dest)
 {
     Gdk.Pixbuf thumb = XdgThumbnailSpec.LoadThumbnail(photo.DefaultVersion.Uri, ThumbnailSize.Large);
     byte[]     buf   = thumb.SaveToBuffer("png");
     SendHeadersAndStartContent(dest, "Content-Type: " + MimeTypeForExt(".png"),
                                "Content-Length: " + buf.Length,
                                "Last-Modified: " + photo.Time.ToString("r"));
     dest.Write(buf, 0, buf.Length);
 }
Beispiel #7
0
 internal byte[] GetActionIcon(Wrapper.Action ac)
 {
     Gdk.Pixbuf pix = ac.RenderIcon(Gtk.IconSize.Menu);
     if (pix == null)
     {
         return(null);
     }
     return(pix.SaveToBuffer("png"));
 }
Beispiel #8
0
 /// <summary>Export the view to the image</summary>
 public System.Drawing.Image Export()
 {
     int width;
     int height;
     MainWidget.GdkWindow.GetSize(out width, out height);
     Gdk.Pixbuf screenshot = Gdk.Pixbuf.FromDrawable(MainWidget.GdkWindow, MainWidget.Colormap, 0, 0, 0, 0, width, height);
     byte[] buffer = screenshot.SaveToBuffer("png");
     MemoryStream stream = new MemoryStream(buffer);
     System.Drawing.Bitmap bitmap = new Bitmap(stream);
     return bitmap;
 }
 public string GenerateImageThumb(string path)
 {
     try {
         path = GenerateRealImagePath(path);
         Gdk.Pixbuf pixbuf  = ImageUtils.GetPixbuf(path, ThumbWidth, ThumbHeight);
         byte[]     imgData = pixbuf.SaveToBuffer("png");
         return(Convert.ToBase64String(imgData));
     } catch (Exception e) {
         Debug.Log("Generate Img Thumb: {0}", e.Message);
         return(null);
     }
 }
Beispiel #10
0
        public static Bitmap BitmapFromPixbuf(Gdk.Pixbuf pixbuf)
        {
            //save bitmap to stream
            byte[] bytes = pixbuf.SaveToBuffer("png");
            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            //verry important: put stream on position 0
            stream.Position = 0;
            //get the pixmap mask
            Bitmap bmp = new Bitmap(stream);

            return(bmp);
        }
Beispiel #11
0
        public static void Write(this BinaryWriter file, Gdk.Pixbuf pixbuf)
        {
            byte[] buf = pixbuf.SaveToBuffer("bmp");

            for (int i = 1; i <= pixbuf.Height; ++i)
            {
                for (int j = 0; j < pixbuf.Width; ++j)
                {
                    int  pos  = buf.Length - i * pixbuf.Width * 3 + j * 3;
                    byte data = (byte)(((int)buf[pos + 0] + (int)buf[pos + 1] + (int)buf[pos + 2]) / 3);
                    file.Write(data);
                }
            }
        }
Beispiel #12
0
        /// <summary>Get screenshot of right hand panel.</summary>
        public System.Drawing.Image GetScreenshotOfRightHandPanel()
        {
            // Create a Bitmap and draw the panel
            int width;
            int height;

            Gdk.Window panelWindow = rightHandView.Child.GdkWindow;
            panelWindow.GetSize(out width, out height);
            Gdk.Pixbuf             screenshot = Gdk.Pixbuf.FromDrawable(panelWindow, panelWindow.Colormap, 0, 0, 0, 0, width, height);
            byte[]                 buffer     = screenshot.SaveToBuffer("png");
            System.IO.MemoryStream stream     = new System.IO.MemoryStream(buffer);
            System.Drawing.Bitmap  bitmap     = new System.Drawing.Bitmap(stream);
            return(bitmap);
        }
        /// <summary>Get screenshot of grid.</summary>
        public System.Drawing.Image GetScreenshot()
        {
            // Create a Bitmap and draw the DataGridView on it.
            int width;
            int height;

            Gdk.Window gridWindow = hbox1.GdkWindow;  // Should we draw from hbox1 or from gridview?
            gridWindow.GetSize(out width, out height);
            Gdk.Pixbuf   screenshot = Gdk.Pixbuf.FromDrawable(gridWindow, gridWindow.Colormap, 0, 0, 0, 0, width, height);
            byte[]       buffer     = screenshot.SaveToBuffer("png");
            MemoryStream stream     = new MemoryStream(buffer);

            System.Drawing.Bitmap bitmap = new Bitmap(stream);
            return(bitmap);
        }
Beispiel #14
0
        public static void Write(this BinaryWriter file, Gdk.Pixbuf pixbuf)
        {
            byte[] buf = pixbuf.SaveToBuffer("bmp");
            // skip header
            for (int i = 54; i < buf.Length; i += 3)
            {
                byte r, g, b;
                r = buf[i + 0];
                g = buf[i + 1];
                b = buf[i + 2];

                byte data = (byte)(((int)r + (int)g + (int)b) / 3);
                file.Write(data);
            }
        }
Beispiel #15
0
        /// <summary>Get screenshot of right hand panel.</summary>
        public System.Drawing.Image GetScreenshotOfRightHandPanel()
        {
#if NETFRAMEWORK
            // Create a Bitmap and draw the panel
            int        width;
            int        height;
            Gdk.Window panelWindow = CurrentRightHandView.MainWidget.GdkWindow;
            panelWindow.GetSize(out width, out height);
            Gdk.Pixbuf             screenshot = Gdk.Pixbuf.FromDrawable(panelWindow, panelWindow.Colormap, 0, 0, 0, 0, width, height);
            byte[]                 buffer     = screenshot.SaveToBuffer("png");
            System.IO.MemoryStream stream     = new System.IO.MemoryStream(buffer);
            System.Drawing.Bitmap  bitmap     = new System.Drawing.Bitmap(stream);
            return(bitmap);
#else
            throw new NotImplementedException();
#endif
        }
Beispiel #16
0
        private static Xwt.Drawing.Image ToXwtImage(Gdk.Pixbuf icon)
        {
            Xwt.Drawing.Image ret;

            var icon2 = new Gdk.Pixbuf(icon.Colorspace, true, icon.BitsPerSample, icon.Width + 1, icon.Height);

            icon2.Fill(0);
            icon.Composite(icon2, 0, 0, icon.Width, icon.Height, 0, 0, 1, 1, Gdk.InterpType.Tiles, 255);

            using (var stream = new MemoryStream(icon2.SaveToBuffer("png")))
            {
                stream.Position = 0;
                ret             = Xwt.Drawing.Image.FromStream(stream);
            }

            return(ret);
        }
Beispiel #17
0
        /// <summary>
        /// Sets the avatar for the person if the person IsMe
        /// </summary>
        public void SetAvatar(Gdk.Pixbuf newAvatar)
        {
            if (!this.IsMe)
            {
                return;
            }

            if (providerUsers.Count > 0)
            {
                byte[] data;

                data = newAvatar.SaveToBuffer("png");

                foreach (ProviderUser user in providerUsers)
                {
                    user.SetAvatar("png", data);
                }
            }
        }
Beispiel #18
0
        /// <summary>Export the view to the image</summary>
        public System.Drawing.Image Export()
        {
#if NETFRAMEWORK
            int width;
            int height;
            MainWidget.GdkWindow.GetSize(out width, out height);
            Gdk.Pixbuf            screenshot = Gdk.Pixbuf.FromDrawable(drawable.GdkWindow, drawable.Colormap, 0, 0, 0, 0, width - 20, height - 20);
            byte[]                buffer     = screenshot.SaveToBuffer("png");
            MemoryStream          stream     = new MemoryStream(buffer);
            System.Drawing.Bitmap bitmap     = new Bitmap(stream);
            return(bitmap);
#else
            var window = new OffscreenWindow();
            window.Add(MainWidget);

            // Choose a good size for the image (which is square).
            int maxX    = (int)nodes.Max(n => n.Location.X);
            int maxY    = (int)nodes.Max(n => n.Location.Y);
            int maxSize = nodes.Max(n => n.Width);
            int size    = Math.Max(maxX, maxY) + maxSize;

            MainWidget.WidthRequest  = size;
            MainWidget.HeightRequest = size;
            window.ShowAll();
            while (GLib.MainContext.Iteration())
            {
                ;
            }

            Gdk.Pixbuf screenshot = window.Pixbuf;
            byte[]     buffer     = screenshot.SaveToBuffer("png");
            window.Dispose();
            using (MemoryStream stream = new MemoryStream(buffer))
            {
                System.Drawing.Bitmap bitmap = new Bitmap(stream);
                return(bitmap);
            }
#endif
        }
Beispiel #19
0
        /// <summary>
        /// Функция загружает изображение из файла любого формата поддерживаемого PixBuf
        /// и возвращает массив байт файла в формете JPG.
        /// </summary>
        /// <returns>The image to jpg bytes.</returns>
        /// <param name="filename">Filename.</param>
        public static byte[] LoadImageToJpgBytes(string filename)
        {
            byte[] imageFile;
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                if (filename.ToLower().EndsWith(".jpg"))
                {
                    using (MemoryStream ms = new MemoryStream()) {
                        fs.CopyTo(ms);
                        imageFile = ms.ToArray();
                    }
                }
                else
                {
                    logger.Info("Конвертация в jpg ...");
                    Gdk.Pixbuf image = new Gdk.Pixbuf(fs);
                    imageFile = image.SaveToBuffer("jpeg");
                }
            }

            return(imageFile);
        }
        public void LoadPhoto(string fileName)
        {
            logger.Info("Загрузка фотографии...");

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
                if (fileName.ToLower().EndsWith(".jpg"))
                {
                    using (MemoryStream ms = new MemoryStream()) {
                        fs.CopyTo(ms);
                        Entity.Photo = ms.ToArray();
                    }
                }
                else
                {
                    logger.Info("Конвертация в jpg ...");
                    Gdk.Pixbuf image = new Gdk.Pixbuf(fs);
                    Entity.Photo = image.SaveToBuffer("jpeg");
                }
            }
            OnPropertyChanged(nameof(SensetiveSavePhoto));
            logger.Info("Ok");
        }
        /// <summary>Get the image from a file name on the clipboard</summary>
        private static System.Drawing.Image GtkGetImageFromText()
        {
            var stringSeparators = new string[] { Environment.NewLine };
            var paths            = GetText().Split(stringSeparators, StringSplitOptions.None);

            foreach (var path in paths)
            {
                if (File.Exists(path))
                {
                    try
                    {
                        var           bytes = File.ReadAllBytes(path);
                        var           buff  = new Gdk.Pixbuf(bytes);
                        TypeConverter tc    = TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
                        return((System.Drawing.Image)tc.ConvertFrom(buff.SaveToBuffer("png")));
                    }
                    catch (Exception e)
                    {
                        Console.Out.WriteLine("{0} is not an image file ({1}).", path, e.Message);
                    }
                }
            }
            return(null);
        }
Beispiel #22
0
 public BitmapImpl(Gdk.Pixbuf pixbuf)
     : base(pixbuf.SaveToBuffer("png"))
 {
 }
Beispiel #23
0
            /// <summary>
            /// Uploads image and returns dictionary of received parameters.
            /// </summary>
            /// <param name="img">Image to upload.</param>
            /// <returns>Dictionary with response parameters.</returns>
            public static Dictionary <string, string> Upload(Gdk.Pixbuf img)
            {
                byte[]         post_content;
                HttpWebRequest request;
                int            basic_length;
                Dictionary <string, string> response = new Dictionary <string, string>();

                StringBuilder post_builder = new StringBuilder();

                post_builder.Append(Parameters.ParamKey).Append("=").Append(Key);
                post_builder.Append("&");
                post_builder.Append(Parameters.ParamImage).Append("=");
                basic_length = post_builder.Length;
                post_builder.Append(UrlEncoder.UrlEncode(Convert.ToBase64String(img.SaveToBuffer("png"))));
                post_content = Encoding.UTF8.GetBytes(post_builder.ToString());

                if (post_content.Length > MaxContentLength)
                {
                    post_builder.Remove(basic_length, post_builder.Length - basic_length);
                    post_builder.Append(UrlEncoder.UrlEncode(Convert.ToBase64String(img.SaveToBuffer("jpeg"))));
                    post_content = Encoding.UTF8.GetBytes(post_builder.ToString());

                    if (post_content.Length > MaxContentLength)
                    {
                        response.Add("FATAL", Catalog.GetString("Image size is too large."));
                        return(response);
                    }
                }

                try
                {
                    request               = (HttpWebRequest)HttpWebRequest.Create(Url);
                    request.Method        = "POST";
                    request.ContentLength = post_content.Length;
                    request.ContentType   = "application/x-www-form-urlencoded";

                    using (Stream writer = request.GetRequestStream())
                    {
                        writer.Write(post_content, 0, post_content.Length);
                    }

                    using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
                    {
                        using (XmlTextReader xmlreader = new XmlTextReader(reader))
                        {
                            ParseResponseXml(response, xmlreader);
                        }
                    }
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    Tools.PrintInfo(ex, typeof(Imgur));
                    response.Add("FATAL", ex.Message);
                }

                return(response);
            }
Beispiel #24
0
		/// <summary>Get the image from a file name on the clipboard</summary>
		private static System.Drawing.Image GtkGetImageFromText()
		{
			var stringSeparators = new string[] { Environment.NewLine };
			var paths = GetText().Split(stringSeparators, StringSplitOptions.None); 

			foreach (var path in paths)
			{
				if (File.Exists(path))
				{
					try
					{
						var bytes = File.ReadAllBytes(path);
						var buff = new Gdk.Pixbuf(bytes);
						TypeConverter tc = TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
						return (System.Drawing.Image)tc.ConvertFrom(buff.SaveToBuffer("png"));
					}
					catch (Exception e)
					{
						Console.Out.WriteLine("{0} is not an image file ({1}).", path, e.Message);
					}
				}
			}
			return null;
		}
Beispiel #25
0
        protected override void AddTrackToDevice(DatabaseTrackInfo track, SafeUri fromUri)
        {
            if (track.PrimarySourceId == DbId)
            {
                return;
            }

            SafeUri new_uri = new SafeUri(GetTrackPath(track, System.IO.Path.GetExtension(fromUri)));

            // If it already is on the device but it's out of date, remove it
            //if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri))
            //RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri)));

            if (!File.Exists(new_uri))
            {
                Directory.Create(System.IO.Path.GetDirectoryName(new_uri.LocalPath));
                File.Copy(fromUri, new_uri, false);

                DatabaseTrackInfo copied_track = new DatabaseTrackInfo(track);
                copied_track.PrimarySource = this;
                copied_track.Uri           = new_uri;

                // Write the metadata in db to the file on the DAP if it has changed since file was modified
                // to ensure that when we load it next time, it's data will match what's in the database
                // and the MetadataHash will actually match.  We do this by comparing the time
                // stamps on files for last update of the db metadata vs the sync to file.
                // The equals on the inequality below is necessary for podcasts who often have a sync and
                // update time that are the same to the second, even though the album metadata has changed in the
                // DB to the feedname instead of what is in the file.  It should be noted that writing the metadata
                // is a small fraction of the total copy time anyway.

                if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime(track.FileModifiedStamp))
                {
                    Log.DebugFormat("Copying Metadata to File Since Sync time >= Updated Time");
                    bool write_metadata = Metadata.SaveTrackMetadataService.WriteMetadataEnabled.Value;
                    bool write_ratings_and_playcounts = Metadata.SaveTrackMetadataService.WriteRatingsAndPlayCountsEnabled.Value;
                    Banshee.Streaming.StreamTagger.SaveToFile(copied_track, write_metadata, write_ratings_and_playcounts);
                }

                copied_track.Save(false);
            }

            if (CoverArtSize > -1 && !String.IsNullOrEmpty(CoverArtFileType) &&
                !String.IsNullOrEmpty(CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0))
            {
                SafeUri cover_uri = new SafeUri(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(new_uri.LocalPath),
                                                                       CoverArtFileName));
                string coverart_id = track.ArtworkId;

                if (!File.Exists(cover_uri) && CoverArtSpec.CoverExists(coverart_id))
                {
                    Gdk.Pixbuf pic = null;

                    if (CoverArtSize == 0)
                    {
                        if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg")
                        {
                            SafeUri local_cover_uri = new SafeUri(Banshee.Base.CoverArtSpec.GetPath(coverart_id));
                            Banshee.IO.File.Copy(local_cover_uri, cover_uri, false);
                        }
                        else
                        {
                            pic = artwork_manager.LookupPixbuf(coverart_id);
                        }
                    }
                    else
                    {
                        pic = artwork_manager.LookupScalePixbuf(coverart_id, CoverArtSize);
                    }

                    if (pic != null)
                    {
                        try {
                            byte []          bytes          = pic.SaveToBuffer(CoverArtFileType);
                            System.IO.Stream cover_art_file = File.OpenWrite(cover_uri, true);
                            cover_art_file.Write(bytes, 0, bytes.Length);
                            cover_art_file.Close();
                        } catch (GLib.GException) {
                            Log.DebugFormat("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType);
                        } finally {
                            Banshee.Collection.Gui.ArtworkManager.DisposePixbuf(pic);
                        }
                    }
                }
            }
        }
Beispiel #26
0
        protected override void AddTrackToDevice(DatabaseTrackInfo track, SafeUri fromUri)
        {
            if (track.PrimarySourceId == DbId)
            {
                return;
            }

            lock (mtp_device) {
                Track  mtp_track = TrackInfoToMtpTrack(track, fromUri);
                bool   video     = track.HasAttribute(TrackMediaAttributes.VideoStream);
                Folder folder    = GetFolderForTrack(track);
                mtp_device.UploadTrack(fromUri.LocalPath, mtp_track, folder, OnUploadProgress);

                // Add/update album art
                if (!video)
                {
                    string key = MakeAlbumKey(track);
                    if (!album_cache.ContainsKey(key))
                    {
                        // LIBMTP 1.0.3 BUG WORKAROUND
                        // In libmtp.c the 'LIBMTP_Create_New_Album' function invokes 'create_new_abstract_list'.
                        // The latter calls strlen on the 'name' parameter without null checking. If AlbumTitle is
                        // null, this causes a sigsegv. Lets be safe and always pass non-null values.
                        Album album = new Album(mtp_device, track.AlbumTitle ?? "", track.AlbumArtist ?? "", track.Genre ?? "", track.Composer ?? "");
                        album.AddTrack(mtp_track);

                        if (supports_jpegs && can_sync_albumart)
                        {
                            ArtworkManager art = ServiceManager.Get <ArtworkManager> ();
                            Exception      ex = null;
                            Gdk.Pixbuf     pic = null;
                            byte[]         bytes = null;
                            uint           width = 0, height = 0;
                            ThreadAssist.BlockingProxyToMain(() => {
                                try {
                                    pic = art.LookupScalePixbuf(track.ArtworkId, thumb_width);
                                    if (pic != null)
                                    {
                                        bytes  = pic.SaveToBuffer("jpeg");
                                        width  = (uint)pic.Width;
                                        height = (uint)pic.Height;
                                    }
                                } catch (Exception e) {
                                    ex = e;
                                }
                            });

                            try {
                                if (ex != null)
                                {
                                    throw ex;
                                }
                                if (bytes != null)
                                {
                                    ArtworkManager.DisposePixbuf(pic);
                                    album.Save(bytes, width, height);
                                    album_cache [key] = Tuple.Create(album, folder);
                                }
                            } catch (Exception e) {
                                Log.Debug("Failed to create MTP Album", e.Message);
                            }
                        }
                        else
                        {
                            album.Save();
                            album_cache[key] = Tuple.Create(album, folder);
                        }
                    }
                    else
                    {
                        Album album = album_cache[key].Item1;
                        album.AddTrack(mtp_track);
                        album.Save();
                    }
                }

                MtpTrackInfo new_track = new MtpTrackInfo(mtp_device, mtp_track);
                new_track.PrimarySource = this;
                new_track.Save(false);
                track_map[new_track.TrackId] = mtp_track;
            }
        }
Beispiel #27
0
        protected void OnButtonLoadPhotoClicked(object sender, EventArgs e)
        {
            FileChooserDialog Chooser = new FileChooserDialog ("Выберите фото для загрузки...",
                (Window)this.Toplevel,
                FileChooserAction.Open,
                "Отмена", ResponseType.Cancel,
                "Загрузить", ResponseType.Accept);

            FileFilter Filter = new FileFilter ();
            Filter.AddPixbufFormats ();
            Filter.Name = "Все изображения";
            Chooser.AddFilter (Filter);

            if ((ResponseType)Chooser.Run () == ResponseType.Accept) {
                Chooser.Hide ();
                logger.Info ("Загрузка фотографии...");

                FileStream fs = new FileStream (Chooser.Filename, FileMode.Open, FileAccess.Read);
                if (Chooser.Filename.ToLower ().EndsWith (".jpg")) {
                    using (MemoryStream ms = new MemoryStream ()) {
                        fs.CopyTo (ms);
                        ImageFile = ms.ToArray ();
                    }
                } else {
                    logger.Info ("Конвертация в jpg ...");
                    Gdk.Pixbuf image = new Gdk.Pixbuf (fs);
                    ImageFile = image.SaveToBuffer ("jpeg");
                }
                fs.Close ();
                buttonSavePhoto.Sensitive = true;
                logger.Info ("Ok");
            }
            Chooser.Destroy ();
        }