Windows forms bitmap как указать путь к файлу

I need to open the bitmap image in the window form using open file dialog (I will load it from drive). The image should fit in the picture box. Here is the code I tried: private void button1_Click(

You have to create an instance of the Bitmap class, using the constructor overload that loads an image from a file on disk. As your code is written now, you’re trying to use the PictureBox.Image property as if it were a method.

Change your code to look like this (also taking advantage of the using statement to ensure proper disposal, rather than manually calling the Dispose method):

private void button1_Click(object sender, EventArgs e)
{
    // Wrap the creation of the OpenFileDialog instance in a using statement,
    // rather than manually calling the Dispose method to ensure proper disposal
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();

            // Create a new Bitmap object from the picture file on disk,
            // and assign that to the PictureBox.Image property
            PictureBox1.Image = new Bitmap(dlg.FileName);
        }
    }
}

Of course, that’s not going to display the image anywhere on your form because the picture box control that you’ve created hasn’t been added to the form. You need to add the new picture box control that you’ve just created to the form’s Controls collection using the Add method. Note the line added to the above code here:

private void button1_Click(object sender, EventArgs e)
{
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();
            PictureBox1.Image = new Bitmap(dlg.FileName);

            // Add the new control to its parent's controls collection
            this.Controls.Add(PictureBox1);
        }
    }
}

tatuska tatuska

13.01.2022

У меня есть папка C#, в этой папке есть ещё одна папка Images, а уже в этой папке находится ещё одна папка Photo, а в папке Photo лежит файл 1.jpg. Как прописать относительный путь к файлу?

C# → Images → Photo → 1.jpg

pictureBox1.Image = Image.FromFile(@»..Photo1.jpg»); (это не работает)

Помогите, пожалуйста.

Иванов Иван Иванов Иван
13.01.2022

Укажи DIR.

Валерий Шестаков Валерий Шестаков
13.01.2022

Относительный путь относительно чего?

  • Как получить путь к ресурсам проекта? C# Windows Forms Пояснение ниже Вот я изменяю изображения пикчерБокса Image.FromFile(«42.jpg») И тут получается, что путь до этого изображения bin/debug/42.jpg, а мне нужно, что бы это изображение бралось из ресурсов проекта, из папки Resources! Пожалуйста помогите! Заранее буду благодарен!
  • Хочу переустановить виндовс с 8.1 до 10.Как разбить диск на 2 части. И указать верное число Чтобы было как на картинке. Не спрашивайте как я до этотго разбивал. Делчл программист Диск на 1Tb
  • Как в bat скрипте указать переход в папку загрузки текущего пользователя винды? Чтобы без конкретного имени пользователя, а у любого кто запустит происходил переход в его папку загрузки?
  • Ребяты, я потерялся в Windows 11 ! Как указать путь к драйверу устройства? Поставил я тут вместо 10-ки 11-ую, решил не обновлением, а начисто. Вопрос такой! Мне нужно указать путь к драйверам сканера МФУ, где этот теперь делается? Имею ввиду, каталог с INF, SYS и прочими файлами.

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Visual Studio 2008 — работа с ресурсами
    , WinForms

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    14.04.10, 16:18

      вообщем делаю проект Windows Forms

      в файле ресурсов

      в ресурсах приложения, а не в отдельном файле есть картинка, как мне эту картинку положить в переменную Image^ ?
      вопрос в догонку: как мне загрузить в ресурсы приложения текстовый файл и потом считывать из него строки?

      PS да, в мсдн я искал, ничего дельного там не нашел

      Сообщение отредактировано: DVD — 14.04.10, 16:43


      GarF1eld



      Сообщ.
      #2

      ,
      14.04.10, 16:30

        Цитата DVD @ 14.04.10, 16:18

        в файле ресурсов есть картинка, как мне эту картинку положить в переменную Image^

        По-моему картинки и хранятся в формате Image. Должно быть что-то вида

        ExpandedWrap disabled

          Image^ img = Resources::MyImage;


        DVD



        Сообщ.
        #3

        ,
        14.04.10, 16:47

          Да, что-то такого вида я пробовал (функции Bitmap::Bitmap, Bitmap::FromResource, Image::FromHbitmap) в различных вариантах — ничего не вышло. А в пространстве имен Resources нет функции MyImage


          Raistlin



          Сообщ.
          #4

          ,
          14.04.10, 17:44

            Full Member

            ***

            Рейтинг (т): 22

            Цитата DVD @ 14.04.10, 16:47

            Да, что-то такого вида я пробовал (функции Bitmap::Bitmap, Bitmap::FromResource, Image::FromHbitmap) в различных вариантах — ничего не вышло. А в пространстве имен Resources нет функции MyImage

            Если в Resources.resx есть графический файл MyImage, то и в классе YourNamespace::Properties::Resources должно быть свойство MyImage типа Bitmap (Image — абстрактный класс, Bitmap — его реализация).

            http://msdn.microsoft.com/en-us/library/7k989cfy(VS.90).aspx

            Сообщение отредактировано: Raistlin — 14.04.10, 17:45


            DVD



            Сообщ.
            #5

            ,
            14.04.10, 18:04

              Короче, я в Студии работаю недавно, поэтому объясните мне пожалуйста как идиоту.
              Я создаю проект WinForms, слева в окне ресурсов добавляю ресурс типа Bitmap, указываю путь к .bmp файлу, называю это ресурс PIC1.
              После этого, мне надо эту картинку загрузить, скажем, на бекграунд формы, или в элемент PictureBox, или поставить фоновым изображением для кнопки.
              Вся задача в том и стоит, чтобы скомпилировав все это дело у меня был один файл, а не исполняемый файл и рядом лежащие картинки.

              Сообщение отредактировано: DVD — 14.04.10, 18:08


              Raistlin



              Сообщ.
              #6

              ,
              14.04.10, 18:08

                Full Member

                ***

                Рейтинг (т): 22

                Цитата DVD @ 14.04.10, 18:04

                Вся задача в том и стоит, чтобы скомпилировав все это дело у меня был один файл

                Так и будет, попробуй.


                DVD



                Сообщ.
                #7

                ,
                14.04.10, 18:13

                  Цитата Raistlin @ 14.04.10, 17:44

                  …в Resources.resx есть графический файл…

                  в проекте нет такого файла, есть app.rc в котором собственно и расположены ссылки на картинки

                  Добавлено 14.04.10, 18:20
                  :blush: извините пожалуйста, надо было в самом начале указать, я пишу на C++ а не на C#

                  Сообщение отредактировано: DVD — 14.04.10, 18:20


                  Raistlin



                  Сообщ.
                  #8

                  ,
                  14.04.10, 18:32

                    Full Member

                    ***

                    Рейтинг (т): 22

                    Да это я сразу не сообразил, что в C++/CLI немного другая схема работы с ресурсами :blush:
                    В общем, если тебе нужно добавить картинку на background формы, просто в свойствах выбираешь BackgroundImage, затем выбираешь нужный файл. Ссылка на картинку добавится в *.resx файле самой формы, и больше делать вообще ничего не надо. И т.д. и т.п…

                    http://forum.developing.ru/showthread.php?16943-Net
                    Ну ничего себе на C++/CLI заморочки…

                    Сообщение отредактировано: Raistlin — 14.04.10, 18:34

                    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                    0 пользователей:

                    • Предыдущая тема
                    • .NET: Общие вопросы
                    • Следующая тема

                    Рейтинг@Mail.ru

                    [ Script execution time: 0,0290 ]   [ 16 queries used ]   [ Generated: 5.02.23, 08:49 GMT ]  

                    Есть ли способ получить путь к файлу типа System.Drawing.Bitmap?

                    Что-то типа:

                    My.Resources.myImg.GetFilePath Или

                    GetFilePath(My.Resources.myImg)

                    Очевидно, что приведенный выше пример не существует. Я просто показываю свое намерение.

                    3 ответа

                    Лучший ответ

                    Совершенно уверен, что это невозможно, так как существует довольно много способов запустить System.Drawing.Bitmap (например, Stream, Uri, другой объект изображения), а этот Bitmap — очень общий объект.

                    В зависимости от технологии, которую вы используете, может быть более специализированный тип изображения, который лучше использовать. Например, если вы используете WPF, обратите внимание на BitmapImage , который сохраняет путь к файлу как свойство UriSource .

                    Если вам действительно нужно работать с System.Drawing.Bitmaps, я бы рекомендовал создать модель, которая содержит как растровое изображение, так и путь к файлу. Как это:

                    {
                        public Bitmap MyImage {get; set; }
                        public string FilePath {get; set; }
                    }
                    


                    0

                    J-DawG
                    6 Фев 2016 в 21:07

                    Возможно, вы захотите создать свой собственный объект:

                    Public Class MyBitmap 
                    Inherits Bitmap 
                    
                    Private _FilePath As String 
                    '------------------------'
                    
                    Public Property FilePath as String 
                    Get 
                    Return _FilePath
                    End Get 
                    
                    ' etc... 
                    

                    Вы можете установить путь и получить его позже из свойства


                    0

                    Zanidd
                    6 Фев 2016 в 21:06

                    Я не уверен, что у ресурсов есть путь, я думаю, что они встроены в приложение, а затем считываются в память (однако я могу ошибаться) .

                    Если вы хотите, чтобы у них был путь, вам нужно сохранить их в файл. Это сохраняет изображение в папке локальных данных приложения:

                    Dim MyImgPath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "myImg.bmp")
                    My.Resources.myImg.Save(MyImgPath, Imaging.ImageFormat.Bmp)
                    

                    Если вы хотите сохранить изображение в той же папке, что и ваше приложение:

                    Dim MyImgPath As String = IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory(), "myImg.bmp")
                    


                    0

                    Visual Vincent
                    6 Фев 2016 в 21:21

                    Я сталкиваюсь с этой странной проблемой, когда пытаюсь создать новое растровое изображение для передачи в метод. Исключение случается, когда в

                    растровое изображение bm = новое растровое изображение («images / cat.jpg»);

                    Я пробовал использовать различные изображения всех размеров, чтобы попробовать и проверить, является ли это проблемой размера файла, однако оказалось, что только 1 существующее изображение в проекте может работать (это изображение кошки).

                    Все остальные изображения возвращают ошибку «Параметр недействителен». Я пытаюсь перестроить проект и разрешить чтение, но все еще не могу заставить его работать.

                    System.ArgumentException was unhandled
                      HResult=-2147024809
                      Message=Parameter is not valid.
                      Source=System.Drawing
                      StackTrace:
                           at System.Drawing.Bitmap..ctor(String filename)
                           at Image_Authentication_Final.RegistrationForm.btnRegister_Click(Object sender, EventArgs e) in c:UsersAccDesktopImage Authentication FinalImage Authentication FinalRegistrationForm.cs:line 176
                           at System.Windows.Forms.Control.OnClick(EventArgs e)
                           at System.Windows.Forms.Button.OnClick(EventArgs e)
                           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
                           at MetroFramework.Controls.MetroButton.OnMouseUp(MouseEventArgs e)
                           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
                           at System.Windows.Forms.Control.WndProc(Message& m)
                           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
                           at System.Windows.Forms.Button.WndProc(Message& m)
                           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
                           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
                           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
                           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
                           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
                           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
                           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
                           at System.Windows.Forms.Application.Run(Form mainForm)
                           at Image_Authentication_Final.Program.Main() in c:UsersAccDesktopImage Authentication FinalImage Authentication FinalProgram.cs:line 19
                           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
                           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
                           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
                           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
                           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
                           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
                           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
                           at System.Threading.ThreadHelper.ThreadStart()
                      InnerException: 
                    

                    Фомин Г.В. 2D-графика в Windows Forms — файл n1.doc

                    Фомин Г.В. 2D-графика в Windows Forms

                    Доступные файлы (1):

                    n1.doc

                    Working with Images, Bitmaps, Icons, and Metafiles

                    GDI+ provides the Bitmap class for working with raster images and the Metafile class for working with vector images. The Bitmap and the Metafile classes both inherit from the Image class.

                    How to: Load and Display Bitmaps

                    To load a bitmap from a file and display that bitmap on the screen, you need a Bitmap object and a Graphics object. The Bitmap class supports several file formats, including BMP, GIF, JPEG, PNG, and TIFF. Pass the name of a file to the Bitmap constructor. After you have created a Bitmap object, pass that Bitmap object to the DrawImage method of a Graphics object.

                    Example

                    This example creates a Bitmap object from a JPEG file and then draws the bitmap with its upper-left corner at (60, 10).

                    The following illustration shows the bitmap drawn at the specified location.

                    Bitmap bitmap = new Bitmap(«Grapes.jpg»);

                    e.Graphics.DrawImage(bitmap, 60, 10);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.

                    Работа с растровыми и векторными изображениями

                    Интерфейс GDI+ содержит класс Bitmap для работы с растровыми изображениями и класс Metafile для работы с векторными изображениями. Классы Bitmap и Metafile наследуют у класса Image.

                    Загрузка и отображение растровых изображений

                    Для загрузки растрового изображения из файла и его вывода на экран следует использовать объекты Bitmap и Graphics. Класс Bitmap поддерживает различные форматы файлов, включая BMP, GIF, JPEG, PNG и TIFF. Имя файла передается в качестве параметра конструктору Bitmap. После создания объекта Bitmap его следует передать как параметр методу DrawImage объекта Graphics.

                    Пример

                    В этом примере создается объект Bitmap на основе файла в формате JPEG и на экране рисуется соответствующее растровое изображение с верхним левым углом в точке (60, 10).

                    На следующем рисунке показано растровое изображение, выведенное на экран в указанном месте.

                    ——

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint.

                    How to: Load and Display Metafiles

                    The Metafile class, which inherits from the Image class, provides methods for recording, displaying, and examining vector images.

                    Example

                    To display a vector image (metafile) on the screen, you need a Metafile object and a Graphics object. Pass the name of a file (or a stream) to a Metafile constructor. After you have created a Metafile object, pass that Metafile object to the DrawImage method of a Graphics object.

                    The example creates a Metafile object from an EMF (enhanced metafile) file and then draws the image with its upper-left corner at (60, 10).

                    The following illustration shows the metafile drawn at the specified location.

                    Metafile metafile = new Metafile(«SampleMetafile.emf»);

                    e.Graphics.DrawImage(metafile, 60, 10);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.

                    Загрузка и отображение метафайлов

                    Класс Metafile, наследующий у класса Image, содержит методы для записи, отображения и проверки векторных изображений.

                    Пример

                    Для отображения векторного изображения (метафайла) на экране следует использовать объекты Metafile и Graphics. Имя файла (или потока) передается в качестве параметра конструктору Metafile. После создания объекта Metafile этот объект Metafile необходимо передать в качестве параметра методу DrawImage объекта Graphics.

                    В примере создается объект Metafile на основе файла в формате EMF (enhanced metafile — расширенный метафайл) и на экране рисуется соответствующее изображение с верхним левым углом в точке (60, 10).

                    На следующем рисунке показан метафайл, выведенный на экран в указанном месте.

                    ———

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint.

                    How to: Crop and Scale Images

                    The Graphics class provides several DrawImage methods, some of which have source and destination rectangle parameters that you can use to crop and scale images.

                    Example

                    The following example constructs an Image object from the disk file Apple.gif. The code draws the entire apple image in its original size. The code then calls the DrawImage method of a Graphics object to draw a portion of the apple image in a destination rectangle that is larger than the original apple image.

                    The DrawImage method determines which portion of the apple to draw by looking at the source rectangle, which is specified by the third, fourth, fifth, and sixth arguments. In this case, the apple is cropped to 75 percent of its width and 75 percent of its height.

                    The DrawImage method determines where to draw the cropped apple and how big to make the cropped apple by looking at the destination rectangle, which is specified by the second argument. In this case, the destination rectangle is 30 percent wider and 30 percent taller than the original image.

                    The following illustration shows the original apple and the scaled, cropped apple.

                    Image image = new Bitmap(«Apple.gif»);

                    // Draw the image unaltered with its upper-left corner at (0, 0).

                    e.Graphics.DrawImage(image, 0, 0);

                    // Make the destination rectangle 30 percent wider and

                    // 30 percent taller than the original image.

                    // Put the upper-left corner of the destination

                    // rectangle at (150, 20).

                    int width = image.Width;

                    int height = image.Height;

                    RectangleF destinationRect = new RectangleF(

                    150,

                    20,

                    1.3f * width,

                    1.3f * height);

                    // Draw a portion of the image. Scale that portion of the image

                    // so that it fills the destination rectangle.

                    RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height);

                    e.Graphics.DrawImage(

                    image,

                    destinationRect,

                    sourceRect,

                    GraphicsUnit.Pixel);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. Make sure to replace Apple.gif with an image file name and path that are valid on your system.

                    Обрезка и масштабирование изображений

                    Класс Graphics включает различные методы DrawImage, некоторые из которых принимают параметры «исходный прямоугольник» и «прямоугольник назначения», используемые для обрезки и масштабирования изображений.

                    Пример

                    В следующем примере создается объект Image на основе файла Apple.gif. Этот код рисует изображение яблока целиком, используя его фактический размер. Затем вызывается метод DrawImage объекта Graphics для рисования фрагмента изображения яблока в прямоугольнике назначения, имеющем больший размер, чем исходное изображение яблока.

                    Метод DrawImage определяет, какой именно фрагмент изображения яблока выводить на экран, анализируя исходный прямоугольник, задаваемый третьим, четвертым, пятым и шестым параметрами метода. В рассматриваемом случае изображение яблока обрезается до 75% его ширины и 75% высоты.

                    Метод DrawImage определяет, где рисовать обрезанное изображение яблока и как его следует масштабировать, анализируя прямоугольник назначения, задаваемый вторым параметром метода. В данном случае прямоугольник назначения на 30% шире и на 30% выше, чем исходное изображение.

                    На следующем рисунке показаны исходное изображение яблока и его масштабированное обрезанное изображение.

                    ——-

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint. Не забудьте заменить путь и имя файла Apple.gif именем файла изображения в вашей системе.

                    How to: Rotate, Reflect, and Skew Images

                    You can rotate, reflect, and skew an image by specifying destination points for the upper-left, upper-right, and lower-left corners of the original image. The three destination points determine an affine transformation that maps the original rectangular image to a parallelogram.

                    Example

                    For example, suppose the original image is a rectangle with upper-left corner at (0, 0), upper-right corner at (100, 0), and lower-left corner at (0, 50). Now suppose you map those three points to destination points as follows.

                    Original point Destination point
                    Upper-left (0, 0) (200, 20)
                    Upper-right (100, 0) (110, 100)
                    Lower-left (0, 50) (250, 30)

                    The following illustration shows the original image and the image mapped to the parallelogram. The original image has been skewed, reflected, rotated, and translated. The x-axis along the top edge of the original image is mapped to the line that runs through (200, 20) and (110, 100). The y-axis along the left edge of the original image is mapped to the line that runs through (200, 20) and (250, 30).

                    Поворот, отражение и наклон изображений

                    Изображение можно поворачивать, отражать и наклонять, указывая точки назначения для верхнего левого, верхнего правого и нижнего левого углов исходного изображения. Эти три точки назначения определяют аффинное преобразование, которое отображает исходное прямоугольное изображение в параллелограмм.

                    Пример

                    Например, предположим, что исходное изображение представляет собой прямоугольник с верхним левым углом в точке (0, 0), верхним правым углом в точке (100, 0) и нижним левым углом в точке (0, 50). Допустим, эти три точки отображаются в соответствующие точки назначения следующим образом.

                    Исходная точка Точка назначения
                    Верхний левый угол (0, 0) (200, 20)
                    Верхний правый угол (100, 0) (110, 100)
                    Нижний левый угол (0, 50) (250, 30)

                    На следующем рисунке показаны как исходное изображение, так и отображение этого изображения в параллелограмм. Исходное изображение было наклонено, отражено, повернуто и сдвинуто. Ось x, расположенная вдоль верхнего края исходного изображения, отображается в линию, проходящую через точки (200, 20) и (110, 100). Ось y, расположенная вдоль левого края исходного изображения, отображается в линию, проходящую через точки (200, 20) и (250, 30).


                    The following illustration shows a similar transformation applied to a photographic image.

                    The following illustration shows a similar transformation applied to a metafile.

                    The following example produces the images shown in the first illustration.

                    Point[] destinationPoints = {

                    new Point(200, 20), // destination for upper-left point of

                    // original

                    new Point(110, 100), // destination for upper-right point of

                    // original

                    new Point(250, 30)}; // destination for lower-left point of

                    // original

                    Image image = new Bitmap(«Stripes.bmp»);

                    // Draw the image unaltered with its upper-left corner at (0, 0).

                    e.Graphics.DrawImage(image, 0, 0);

                    // Draw the image mapped to the parallelogram.

                    e.Graphics.DrawImage(image, destinationPoints);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgse, which is a parameter of the Paint event handler. Make sure to replace Stripes.bmp with the path to an image that is valid on your system.
                    На приведенном ниже рисунке показано такое же преобразование, примененное к фотографическому изображению.

                    ——

                    На следующем рисунке показано аналогичное преобразование, примененное к метафайлу.

                    В следующем примере создаются изображения, показанные на первом рисунке.

                    —

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint. Не забудьте заменить путь и имя файла Stripes.bmp именем файла изображения и путем к нему в вашей системе.

                    How to: Use Interpolation Mode to Control Image Quality During Scaling

                    The interpolation mode of a Graphics object influences the way GDI+ scales (stretches and shrinks) images. The InterpolationMode enumeration defines several interpolation modes, some of which are shown in the following list:

                    • NearestNeighbor
                    • Bilinear
                    • HighQualityBilinear
                    • Bicubic
                    • HighQualityBicubic

                    To stretch an image, each pixel in the original image must be mapped to a group of pixels in the larger image. To shrink an image, groups of pixels in the original image must be mapped to single pixels in the smaller image. The effectiveness of the algorithms that perform these mappings determines the quality of a scaled image. Algorithms that produce higher-quality scaled images tend to require more processing time. In the preceding list, NearestNeighbor is the lowest-quality mode and HighQualityBicubic is the highest-quality mode.

                    To set the interpolation mode, assign one of the members of the InterpolationMode enumeration to the InterpolationMode property of a Graphics object.

                    Example

                    The following example draws an image and then shrinks the image with three different interpolation modes.

                    The following illustration shows the original image and the three smaller images.

                    Использование режима интерполяции для управления качеством изображений при масштабировании

                    Режим интерполяции объекта Graphics влияет на способ, с помощью которого GDI+ масштабирует (растягивает и сжимает) изображения. Перечисление InterpolationMode определяет различные режимы интерполяции, некоторые из которых приведены в следующем списке:

                    • NearestNeighbor
                    • Bilinear
                    • HighQualityBilinear
                    • Bicubic
                    • HighQualityBicubic

                    Чтобы растянуть изображение, каждая точка этого исходного изображения должна быть сопоставлена группе точек увеличенного изображения. Чтобы сжать изображение, группы точек этого исходного изображения должны быть сопоставлены отдельным точкам уменьшенного изображения. Качество масштабированного изображения определяется алгоритмами, используемыми для осуществления этих сопоставлений. Алгоритмы, создающие более качественные масштабированные изображения, обычно требуют больших затрат машинного времени. Из методов интерполяции, приведенных в предыдущем списке, NearestNeighbor обеспечивает наихудшее качество, а HighQualityBicubic — наилучшее.

                    Чтобы установить режим интерполяции, присвойте один из членов перечисления InterpolationMode свойству InterpolationMode объекта Graphics.

                    Пример

                    В следующем примере рисуется изображение, которое затем сжимается с использованием трех различных способов интерполяции.

                    На следующем рисунке показаны как исходное изображение, так и три варианта уменьшенного изображения.

                    ————

                    Image image = new Bitmap(«GrapeBunch.bmp»);

                    int width = image.Width;

                    int height = image.Height;

                    // Draw the image with no shrinking or stretching.

                    e.Graphics.DrawImage(

                    image,

                    new Rectangle(10, 10, width, height), // destination rectangle

                    0,

                    0, // upper-left corner of source rectangle

                    width, // width of source rectangle

                    height, // height of source rectangle

                    GraphicsUnit.Pixel,

                    null);

                    // Shrink the image using low-quality interpolation.

                    e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;

                    e.Graphics.DrawImage(

                    image,

                    new Rectangle(10, 250, (int)(0.6 * width), (int)(0.6 * height)),

                    // destination rectangle

                    0,

                    0, // upper-left corner of source rectangle

                    width, // width of source rectangle

                    height, // height of source rectangle

                    GraphicsUnit.Pixel);

                    // Shrink the image using medium-quality interpolation.

                    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;

                    e.Graphics.DrawImage(

                    image,

                    new Rectangle(150, 250, (int)(0.6 * width), (int)(0.6 * height)),

                    // destination rectangle

                    0,

                    0, // upper-left corner of source rectangle

                    width, // width of source rectangle

                    height, // height of source rectangle

                    GraphicsUnit.Pixel);

                    // Shrink the image using high-quality interpolation.

                    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    e.Graphics.DrawImage(

                    image,

                    new Rectangle(290, 250, (int)(0.6 * width), (int)(0.6 * height)),

                    // destination rectangle

                    0,

                    0, // upper-left corner of source rectangle

                    width, // width of source rectangle

                    height, // height of source rectangle

                    GraphicsUnit.Pixel);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.
                    ————-

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint.

                    How to: Create Thumbnail Images

                    A thumbnail image is a small version of an image. You can create a thumbnail image by calling the GetThumbnailImage method of an Image object.

                    Example

                    The following example constructs an Image object from the file Compass.bmp. The original image has a width of 640 pixels and a height of 479 pixels. The code creates a thumbnail image that has a width of 100 pixels and a height of 100 pixels.

                    The following illustration shows the thumbnail image.

                    Image image = new Bitmap(«Compass.bmp»);

                    Image pThumbnail = image.GetThumbnailImage(100, 100, null, new

                    IntPtr());

                    e.Graphics.DrawImage(

                    pThumbnail,

                    10,

                    10,

                    pThumbnail.Width,

                    pThumbnail.Height);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler.

                    Создание эскизов изображений

                    Эскиз изображения — это сильно уменьшенный вариант изображения. Чтобы создать эскиз изображения, следует вызвать метод GetThumbnailImage объекта Image.

                    Пример

                    В следующем примере показано создание объекта Image из файла Compass.bmp. Исходное изображение имеет ширину 640 точек и высоту 479 точек. Приведенный ниже код создает эскиз изображения, имеющий ширину 100 точек и высоту 100 точек.

                    Эскиз изображения показан на следующем рисунке.

                    ——

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint.

                    How to: Improve Performance by Avoiding Automatic Scaling

                    GDI+ may automatically scale an image as you draw it, which would decrease performance. Alternatively, you can control the scaling of the image by passing the dimensions of the destination rectangle to the DrawImage method.

                    For example, the following call to the DrawImage method specifies an upper-left corner of (50, 30) but does not specify a destination rectangle.

                    e.Graphics.DrawImage(image, 50, 30); // upper-left corner at (50, 30)

                    Although this is the easiest version of the DrawImage method in terms of the number of required arguments, it is not necessarily the most efficient. If the resolution used by GDI+ (usually 96 dots per inch) is different from the resolution stored in the Image object, then the DrawImage method will scale the image. For example, suppose an Image object has a width of 216 pixels and a stored horizontal resolution value of 72 dots per inch. Because 216/72 is 3, DrawImage will scale the image so that it has a width of 3 inches at a resolution of 96 dots per inch. That is, DrawImage will display an image that has a width of 96×3 = 288 pixels.

                    Even if your screen resolution is different from 96 dots per inch, GDI+ will probably scale the image as if the screen resolution were 96 dots per inch. That is because a GDI+ Graphics object is associated with a device context, and when GDI+ queries the device context for the screen resolution, the result is usually 96, regardless of the actual screen resolution. You can avoid automatic scaling by specifying the destination rectangle in the DrawImage method.

                    Повышение производительности за счет отключения автоматического масштабирования

                    Интерфейс GDI+ поддерживает автоматическое масштабирование выводимого на экран изображения, но этот процесс снижает производительность. Для управления масштабом изображения можно также передавать методу DrawImage значения ширины и высоты прямоугольника назначения.

                    Например, в показанном ниже вызове метода DrawImage указывается верхний левый угол с координатами (50, 30), а прямоугольник назначения не определяется.

                    e.Graphics.DrawImage(image, 50, 30); // upper-left corner at (50, 30)

                    Хотя это простейший вариант метода DrawImage, если судить по количеству требуемых параметров, однако он необязательно является самым эффективным. Если разрешение (обычно 96 точек на дюйм), используемое интерфейсом GDI+, отличается от разрешения, указанного в объекте Image, то метод DrawImage осуществляет масштабирование изображения. Например, предположим, что объект Image имеет в ширину 216 точек, а хранящееся в этом объекте разрешение по горизонтали составляет 72 точки на дюйм. Поскольку 216/72 равно 3, метод DrawImage осуществляет масштабирование изображения таким образом, чтобы конечное изображение имело в ширину 3 дюйма при разрешении 96 точек на дюйм. Таким образом, метод DrawImage выводит изображение шириной 96 x 3 = 288 точек.

                    Даже если экранное разрешение отличается от 96 точек на дюйм, вполне вероятно, что интерфейс GDI+ все равно осуществит масштабирование изображения, как если бы разрешение составляло 96 точек на дюйм. Это происходит потому, что объект Graphics интерфейса GDI+ связан с программной средой устройства и, когда GDI+ запрашивает экранное разрешение у программной среды устройства, результатом обычно является 96, независимо от фактического экранного разрешения. Чтобы предотвратить автоматическое масштабирование, можно указать в параметрах метода DrawImage прямоугольник назначения.

                    Example

                    The following example draws the same image twice. In the first case, the width and height of the destination rectangle are not specified, and the image is automatically scaled. In the second case, the width and height (measured in pixels) of the destination rectangle are specified to be the same as the width and height of the original image. The following illustration shows the image rendered twice.

                    Image image = new Bitmap(«Texture.jpg»);
                    e.Graphics.DrawImage(image, 10, 10);

                    e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. Replace Texture.jpg with an image name and path that are valid on your system.

                    Пример

                    В следующем примере одно и то же изображение рисуется два раза. В первом случае ширина и высота прямоугольника назначения не указываются и осуществляется автоматическое масштабирование изображения. Во втором случае ширина и высота прямоугольника назначения задаются явным образом (в точках) равными соответственно ширине и высоте исходного изображения. На приведенном ниже рисунке показано дважды выведенное на экран изображение.


                    —

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint. Не забудьте заменить путь и имя файла Replace Texture.jpg именем файла изображения в вашей системе.

                    How to: Read Image Metadata

                    Some image files contain metadata that you can read to determine features of the image. For example, a digital photograph might contain metadata that you can read to determine the make and model of the camera used to capture the image. With GDI+, you can read existing metadata, and you can also write new metadata to image files.

                    GDI+ stores an individual piece of metadata in a PropertyItem object. You can read the PropertyItems property of an Image object to retrieve all the metadata from a file. The PropertyItems property returns an array of PropertyItem objects.

                    A PropertyItem object has the following four properties: Id, Value, Len, and Type.

                    Id

                    A tag that identifies the metadata item. Some values that can be assigned to Id are shown in the following table.

                    Hexadecimal value Description
                    0x0320

                    0x010F

                    0x0110

                    0x9003

                    0x829A

                    0x5090

                    0x5091

                    Image title

                    Equipment manufacturer

                    Equipment model

                    ExifDTOriginal

                    Exif exposure time

                    Luminance table

                    Chrominance table

                    Value

                    An array of values. The format of the values is determined by the Type property.

                    Len

                    The length (in bytes) of the array of values pointed to by the Value property.

                    Чтение метаданных изображения

                    Некоторые файлы с изображениями содержат метаданные, которые можно прочитать, чтобы определить свойства изображения. Например, цифровая фотография может содержать метаданные, которые позволяют определить модель камеры, с помощью которой была получена данная фотография. С помощью интерфейса GDI+ можно считывать существующие метаданные, а также добавлять новые метаданные в файлы с изображениями.

                    Интерфейс GDI+ хранит каждый отдельный блок метаданных в объекте PropertyItem. Чтобы получить все метаданные файла, можно прочитать свойство PropertyItems объекта Image. Свойство PropertyItems возвращает массив объектов PropertyItem.

                    Объект PropertyItem имеет следующие четыре свойства: Id, Value, Len и Type.

                    Id

                    Тег, идентифицирующий блок метаданных. Некоторые из значений, которые может принимать Id, приводятся в следующей таблице.

                    Шестнадцатеричное значение Описание
                    0x0320

                    0x010F

                    0x0110

                    0x9003

                    0x829A

                    0x5090

                    0x5091

                    Название изображения

                    Производитель оборудования

                    Модель оборудования

                    ExifDTOriginal

                    Exif — время выдержки

                    Таблица светимости

                    Таблица хроматических данных

                    Значение

                    Массив значений. Формат значений определяется свойством Type.

                    Len

                    Размер (в байтах) массива значений, на который указывает свойство Value.

                    Type

                    The data type of the values in the array pointed to by the Value property. The formats indicated by the Type property values are shown in the following table

                    Numeric value Description
                    1 A Byte
                    2 An array of Byte objects encoded as ASCII
                    3 A 16-bit integer
                    4 A 32-bit integer
                    5 An array of two Byte objects that represent a rational number
                    6 Not used
                    7 Undefined
                    8 Not used
                    9 SLong
                    10 SRational
                    Example
                    Description

                    The following code example reads and displays the seven pieces of metadata in the file FakePhoto.jpg. The second (index 1) property item in the list has Id 0x010F (equipment manufacturer) and Type 2 (ASCII-encoded byte array). The code example displays the value of that property item.

                    Type

                    Тип элементов массива, на который указывает свойство Value. Типы, определяемые по значению свойства Type, приводятся в следующей таблице.

                    Числовое значение Описание
                    1 Элемент Byte.
                    2 Массив объектов Byte в кодировке ASCII
                    3 16-битное целое число
                    4 32-битное целое число
                    5 Массив из двух объектов Byte, представляющих рациональное число
                    6 Не используется
                    7 Не определено
                    8 Не используется
                    9 SLong
                    10 SRational
                    Пример
                    Описание

                    В следующем примере кода осуществляется считывание и отображение семи блоков метаданных из файла FakePhoto.jpg. Второе свойство в списке (индекс 1) имеет значение Id 0x010F (производитель оборудование) и Type 2 (массив объектов byte в кодировке ASCII). В примере кода отображается значение данного свойства.
                    The code produces output similar to the following:

                    Property Item 0

                    id: 0x320

                    type: 2

                    length: 16 bytes

                    Property Item 1

                    id: 0x10f

                    type: 2

                    length: 17 bytes

                    Property Item 2

                    id: 0x110

                    type: 2

                    length: 7 bytes

                    Property Item 3

                    id: 0x9003

                    type: 2

                    length: 20 bytes

                    Property Item 4

                    id: 0x829a

                    type: 5

                    length: 8 bytes

                    Property Item 5

                    id: 0x5090

                    type: 3

                    length: 128 bytes

                    Property Item 6

                    id: 0x5091

                    type: 3

                    length: 128 bytes

                    The equipment make is Northwind Camera.
                    Результат выполнения этого кода будет выглядеть примерно следующим образом:

                    ———

                    Code
                    // Create an Image object.

                    Image image = new Bitmap(@»c:FakePhoto.jpg»);

                    // Get the PropertyItems property from image.

                    PropertyItem[] propItems = image.PropertyItems;

                    // Set up the display.

                    Font font = new Font(«Arial», 12);

                    SolidBrush blackBrush = new SolidBrush(Color.Black);

                    int X = 0;

                    int Y = 0;

                    // For each PropertyItem in the array, display the ID, type, and

                    // length.

                    int count = 0;

                    foreach (PropertyItem propItem in propItems)

                    {

                    e.Graphics.DrawString(

                    «Property Item » + count.ToString(),

                    font,

                    blackBrush,

                    X, Y);

                    Y += font.Height;

                    e.Graphics.DrawString(

                    » iD: 0x» + propItem.Id.ToString(«x»),

                    font,

                    blackBrush,

                    X, Y);

                    Y += font.Height;

                    e.Graphics.DrawString(

                    » type: » + propItem.Type.ToString(),

                    font,

                    blackBrush,

                    X, Y);

                    Y += font.Height;

                    e.Graphics.DrawString(

                    » length: » + propItem.Len.ToString() + » bytes»,

                    font,

                    blackBrush,

                    X, Y);

                    Y += font.Height;

                    count++;

                    }

                    // Convert the value of the second property to a string, and display

                    // it.

                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

                    string manufacturer = encoding.GetString(propItems[1].Value);

                    e.Graphics.DrawString(

                    «The equipment make is » + manufacturer + «.»,

                    font,

                    blackBrush,

                    X, Y);

                    Compiling the Code

                    The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. Replace FakePhoto.jpg with an image name and path valid on your system.

                    Код

                    ————-

                    Компиляция кода

                    Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint. Подставьте вместо FakePhoto.jpg имя имеющегося на вашем компьютере файла изображения и путь к нему.

                    How to: Create a Bitmap at Run Time

                    This example creates and draws in a Bitmap object and displays it in an existing Windows Forms PictureBox control.

                    Example
                    PictureBox pictureBox1 = new PictureBox();

                    public void CreateBitmapAtRuntime()

                    {

                    pictureBox1.Size = new Size(210, 110);

                    this.Controls.Add(pictureBox1);
                    Bitmap flag = new Bitmap(200, 100);

                    Graphics flagGraphics = Graphics.FromImage(flag);

                    int red = 0;

                    int white = 11;

                    while (white <= 100) {

                    flagGraphics.FillRectangle(Brushes.Red, 0, red, 200,10);

                    flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);

                    red += 20;

                    white += 20;

                    }

                    pictureBox1.Image = flag;
                    }

                    Compiling the Code

                    This example requires:

                    • A Windows Form that imports the System, System.Drawing and System.Windows.Forms assemblies.

                    Создание растрового изображения во время выполнения

                    В этом примере демонстрируется создание объекта Bitmap и рисование в нем, после чего объект отображается на существующей форме Windows Forms в элементе управления PictureBox.

                    Пример

                    ——

                    Компиляция кода

                    Для этого примера требуются следующие компоненты.

                    • Форма Windows Form, импортирующая сборки System, System.Drawing и System.Windows.Forms.

                    How to: Extract the Icon Associated with a File in Windows Forms

                    Many files have embedded icons that provide a visual representation of the associated file type. For example, Microsoft Word documents contain an icon that identifies them as Word documents. When displaying files in a list control or table control, you may want to display the icon representing the file type next to each file name. You can do this easily by using the ExtractAssociatedIcon method.

                    Example

                    The following code example demonstrates how to extract the icon associated with a file and display the file name and its associated icon in a ListView control.

                    ListView listView1;

                    ImageList imageList1;
                    public void ExtractAssociatedIconEx()

                    {

                    // Initialize the ListView, ImageList and Form.

                    listView1 = new ListView();

                    imageList1 = new ImageList();

                    listView1.Location = new Point(37, 12);

                    listView1.Size = new Size(151, 262);

                    listView1.SmallImageList = imageList1;

                    listView1.View = View.SmallIcon;

                    this.ClientSize = new System.Drawing.Size(292, 266);

                    this.Controls.Add(this.listView1);

                    this.Text = «Form1»;
                    // Get the c: directory.

                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@»c:»);
                    ListViewItem item;

                    listView1.BeginUpdate();

                    Извлечение связанного с файлом значка в Windows Forms

                    У многих файлов имеются внедренные значки, которые служат для визуального представления соответствующего типа файла. Например, документы Microsoft Word содержат значок, который указывает на то, что эти файлы являются документами Word. При отображении файлов в таких элементах управления, как список или таблица, может потребоваться поместить рядом с именем файла значок, обозначающий тип этого файла. Для этого достаточно вызвать метод ExtractAssociatedIcon.

                    Пример

                    В следующем примере показано, как извлечь связанный с файлом значок и вывести его на экран рядом именем файла в элементе управления ListView.

                    ——————-

                    // For each file in the c: directory, create a ListViewItem

                    // and set the icon to the icon extracted from the file.

                    foreach (FileInfo file in dir.GetFiles())

                    {

                    // Set a default icon for the file.

                    Icon iconForFile = SystemIcons.WinLogo;
                    item = new ListViewItem(file.Name, 1);

                    iconForFile = Icon.ExtractAssociatedIcon(file.FullName);
                    // Check to see if the image collection contains an image

                    // for this extension, using the extension as a key.

                    if (!imageList1.Images.ContainsKey(file.Extension))

                    {

                    // If not, add the image to the image list.

                    iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName);

                    imageList1.Images.Add(file.Extension, iconForFile);

                    }

                    item.ImageKey = file.Extension;

                    listView1.Items.Add(item);

                    }

                    listView1.EndUpdate();

                    }

                    Compiling the Code

                    To compile the example:

                    • Paste the preceding code into a Windows Form, and call the ExtractAssociatedIconExample method from the form’s constructor or Load event-handling method.

                    You will need to make sure that your form imports the System.IO namespace.

                    ——-

                    Компиляция кода

                    Чтобы скомпилировать этот пример, выполните следующие действия.

                    • Вставьте предыдущий код в форму Windows Form и вызовите метод ExtractAssociatedIconExample из конструктора или метода обработки события формы Load.

                    Необходимо проверить, что форма импортирует пространство имен System.IO.

                    Понравилась статья? Поделить с друзьями:
                  • Windows forms application visual studio 2013
                  • Windows forms application c как установить
                  • Windows forms application c visual studio 2019
                  • Windows forms app net framework visual studio
                  • Windows forms anchor как правильно пользоваться