Не могу найти элемент управления ImageBox
Где найти элемент управления, похожий на Toolbox в VS
Добрый день. Помогите с поиском компоненты. Пишу в Visual Studio 2008 на C# приложение Windows.
Найти элемент управления с нулевым размером в дизайнере
Такой вопрос: ковыряю чужую прогу, на ней, на винформах мульен конролов — закладки, слои и.
Считывание картинки из одного ImageBox и установка ее в другой ImageBox
Есть два бокса для картинок. В первом боксе уже установлено изображение, а второй бокс пустует.
Не могу поместить на форму элемент управления
Раньше устанавливал VS 2010 express все запускалось без ошибок. Недавно переустановил ось(win7 64).
ImageBox
Иерархия наследования
Описание
Компонент ImageBox предназначен для загрузки и отображения изображений.
Работа с компонентом
Для загрузки изображения необходимо выполнить одно из следующих действий:
в режиме дизайна формы дважды щелкнуть по компоненту на форме.
в инспекторе объектов нажать кнопку свойства Image.
выполнить команду контекстного меню « Редактировать » для компонента.
После этого будет открыт редактор изображения компонента:
При нажатии кнопки « Загрузить » будет выведен стандартный диалог выбора файла, который в дальнейшем будет отображаться в компоненте. В список доступных изображений входят файлы в форматах: *.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.png;*.tif;*.tiff. Если размеры выбранной картинки больше размеров окна редактирования, то изображение будет автоматически масштабировано.
В группе « Фиксировать область » можно настроить области изображения, которые не будут масштабироваться при отображении. Для этого фоновое изображение условно разбивается на 9 частей:
При отрисовке изображения части A, C, G, I не подлежат масштабированию. Части B, H подлежат масштабированию только по горизонтали. Части D, F подлежат масштабированию только по вертикали. Часть E масштабируется полностью.
Флаг « Отображать области » управляет отображением красных линий, отделяющих фиксированные области изображения от масштабированных. Фиксированные области отображаются в том виде, в каком они содержатся в исходном файле. Вся остальная область изображения масштабируется в соответствии с размерами компонента ImageBox . Размеры фиксированной области задаются в пикселях и ограничены размерами загруженного изображения.
Флаг « Растянуть изображение » позволяет растянуть загруженное изображение на всю область окна редактирования.
Кнопка « Сохранить » позволяет сохранить изображение, загруженное в компонент.
Для настройки фонового изображения с отступами через ядро реализован специальный класс GxRectangleTransformImage. Параметры фиксированных отступов задаются в свойстве Margins.
Предупреждение: imageftbbox() [function.imageftbbox] — то, что эта ошибка
Я получил эту ошибку на моем генерации изображения сценария:
Предупреждение: imageftbbox() [function.imageftbbox]: Проблема загрузки глифов:
Я думаю, из-за этого я не могу правильно генерировать изображения из текста — как это исправить!
Создан 15 июл. 09 2009-07-15 08:29:06 Ali
Just double checked загрузил мой файл шрифта снова — теперь все ясно, спасибо за быстрый ответ man: D – Ali 15 июл. 09 2009-07-15 08:50:39
3 ответа
возникла проблема с загрузкой файла шрифта. проверьте путь, имя файла и т. д.
Создан 15 июл. 09 2009-07-15 08:39:47 dusoft
Если у вас есть проблема с файлом path/filename, вы получите предупреждение «Неверное имя шрифта».
«Проблема загрузки глифа» означает, что существует реальная проблема с форматом файла, то есть FT_Load_Glyph библиотеки gd не смог интерпретировать определение шрифта.
Создан 15 июл. 09 2009-07-15 08:58:01 VolkerK
Возможно, ваша сборка php не скомпилирована с помощью freetype2. Проверьте настройки конфигурации вашей php-сборки, запустив phpinfo() с помощью php-скрипта.
Создан 10 дек. 09 2009-12-10 00:49:30 Nick Miller
imageftbbox
(PHP 4 >= 4.0.7, PHP 5)
imageftbbox — Give the bounding box of a text using fonts via freetype2
Описание
This function calculates and returns the bounding box in pixels for a FreeType text.
Список параметров
The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
Angle in degrees in which text will be measured.
The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading ‘/’ by appending ‘.ttf’ to the filename and searching along a library-defined font path.
The string to be measured.
Key | Type | Meaning | linespacing | float | Defines drawing linespacing |
---|
Возвращаемые значения
imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:
lower left corner, X position | |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
The points are relative to the text regardless of the angle, so «upper left» means in the top left-hand corner seeing the text horizontally.
Примеры
Пример #1 imageftbbox() example
// Create a 300×150 image
$im = imagecreatetruecolor ( 300 , 150 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
// Set the background to be white
imagefilledrectangle ( $im , 0 , 0 , 299 , 299 , $white );
// Path to our font file
$font = ‘./arial.ttf’ ;
// First we create our bounding box
$bbox = imageftbbox ( 10 , 0 , $font , ‘The PHP Documentation Group’ );
// This is our cordinates for X and Y
$x = $bbox [ 0 ] + ( imagesx ( $im ) / 2 ) — ( $bbox [ 4 ] / 2 ) — 5 ;
$y = $bbox [ 1 ] + ( imagesy ( $im ) / 2 ) — ( $bbox [ 5 ] / 2 ) — 5 ;
imagefttext ( $im , 10 , 0 , $x , $y , $black , $font , ‘The PHP Documentation Group’ );
// Output to browser
header ( ‘Content-type: image/png’ );
imagepng ( $im );
imagedestroy ( $im );
?>
Примечания
Замечание: Эта функция нуждается в GD версии 2.0.1 или выше.
Замечание: Эта функция доступна только в случае, если PHP был скомплирован с поддержкой freetype ( —with-freetype-dir=DIR )
Что такое код imageftbbox
Подскажите, кто в теме:
который на локальном компе (установлен денвер с настройками по умолчанию) — работает, а на хостинге выдаёт ошибку:
Warning: imagettftext() [function.imagettftext]: any2eucjp(): invalid code in input string in .
при замене строчки:
$text = iconv(«WINDOWS-1251», «UTF-8», $text);
на
$text = iconv(«WINDOWS-1251», «EUC-JP», $text);
код начинает работать, но с ошибками — не всегда корректно отображает текст, а иногда тоже вылетает со схожей ошибкой.
Меню пользователя remaikee |
Посмотреть профиль |
Отправить личное сообщение для remaikee |
Найти ещё сообщения от remaikee |
09.05.2009, 02:02 | #2 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Меню пользователя Артем Юров |
Посмотреть профиль |
Найти ещё сообщения от Артем Юров |
09.05.2009, 10:45 | #3 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Меню пользователя remaikee |
Посмотреть профиль |
Отправить личное сообщение для remaikee |
Найти ещё сообщения от remaikee |
11.05.2009, 22:17 | #4 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Key | Type | Meaning | linespacing | float | Defines drawing linespacing |
---|
Возвращаемые значения
imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:
lower left corner, X position | |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
The points are relative to the text regardless of the angle, so «upper left» means in the top left-hand corner seeing the text horizontally.
Примеры
Пример #1 imageftbbox() example
// Create a 300×150 image
$im = imagecreatetruecolor ( 300 , 150 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
// Set the background to be white
imagefilledrectangle ( $im , 0 , 0 , 299 , 299 , $white );
// Path to our font file
$font = ‘./arial.ttf’ ;
// First we create our bounding box
$bbox = imageftbbox ( 10 , 0 , $font , ‘The PHP Documentation Group’ );
// This is our cordinates for X and Y
$x = $bbox [ 0 ] + ( imagesx ( $im ) / 2 ) — ( $bbox [ 4 ] / 2 ) — 5 ;
$y = $bbox [ 1 ] + ( imagesy ( $im ) / 2 ) — ( $bbox [ 5 ] / 2 ) — 5 ;
imagefttext ( $im , 10 , 0 , $x , $y , $black , $font , ‘The PHP Documentation Group’ );
// Output to browser
header ( ‘Content-type: image/png’ );
imagepng ( $im );
imagedestroy ( $im );
?>
Примечания
Замечание: Эта функция нуждается в GD версии 2.0.1 или выше.
Замечание: Эта функция доступна только в случае, если PHP был скомплирован с поддержкой freetype ( —with-freetype-dir=DIR )
pchart ошибка: Сообщение: imageftbbox () [function.imageftbbox]: Invalid имя файла шрифта
November 2020
1.8k раз
Я попробовал несколько различных способов, и сейчас я быть как явные, как я могу. Я использую XAMPP на Windows 7 с PHP / pChart. В моем коде у меня есть:
Я включаю «/» перед шрифтами, так что библиотека не accidentaly присоединять .ttf, который я прочитал могу произойти в некоторых случаях.
Любая помощь в этом вопросе было бы весьма признателен.
1 ответы
Я использую несколько дней назад pChart и получил ту же ошибку, когда я копировать-вставить пример кода из pChart документации. Просто попробуйте добавить расположение шрифта, добавив полный абсолютный путь к нему:
И я хранить библиотеку pChart в [root]/libs/pChart/ . Конечно , у должны быть уверены , что у вас папку «шрифты». Мой код работает отлично с ним. Так что я думаю , ваша ошибка была в попытке выделить систему шрифты вместо локальных включает.
imageftbbox
(PHP 4 >= 4.0.7, PHP 5, PHP 7)
imageftbbox — Give the bounding box of a text using fonts via freetype2
Description
This function calculates and returns the bounding box in pixels for a FreeType text.
Parameters
The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
Angle in degrees in which text will be measured.
The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading ‘/’ by appending ‘.ttf’ to the filename and searching along a library-defined font path.
The string to be measured.
Key | Type | Meaning |
---|---|---|
linespacing | float | Defines drawing linespacing |
Return Values
imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:
lower left corner, X position | |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
The points are relative to the text regardless of the angle , so «upper left» means in the top left-hand corner seeing the text horizontally.
Examples
Example #1 imageftbbox() example
// Create a 300×150 image
$im = imagecreatetruecolor ( 300 , 150 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
// Set the background to be white
imagefilledrectangle ( $im , 0 , 0 , 299 , 299 , $white );
// Path to our font file
$font = ‘./arial.ttf’ ;
// First we create our bounding box
$bbox = imageftbbox ( 10 , 0 , $font , ‘The PHP Documentation Group’ );
// This is our cordinates for X and Y
$x = $bbox [ 0 ] + ( imagesx ( $im ) / 2 ) — ( $bbox [ 4 ] / 2 ) — 5 ;
$y = $bbox [ 1 ] + ( imagesy ( $im ) / 2 ) — ( $bbox [ 5 ] / 2 ) — 5 ;
imagefttext ( $im , 10 , 0 , $x , $y , $black , $font , ‘The PHP Documentation Group’ );
// Output to browser
header ( ‘Content-Type: image/png’ );
imagepng ( $im );
imagedestroy ( $im );
?>
Notes
Note: This function requires GD 2.0.1 or later (2.0.28 or later is recommended).
Note: This function is only available if PHP is compiled with freetype support ( —with-freetype-dir=DIR )
User Contributed Notes
imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:
0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position
The points are relative to the text regardless of the angle, so «upper left» means in the top left-hand corner seeing the text horizontally.
ImageFTBBox returns a bounding box, not metrics, as some (most?) of the notes above seem to assume. The 8 values it returns specify the 4 corners of this bounding box. So to properly determine the width and height of a string you need to do:
$bbox = ImageFTBBox(. );
$w >$height = abs($bbox[1]) + abs($bbox[5]); // distance from top to bottom
Here is a handy example I used to center «dynamic text» onto an image.
Ex. Say you want to center a clients IP Address onto a picture.
$details = imageftbbox($fontsize, 0, $font, $ip, array(«linespacing» => 1));
$xcoord = ($imgwidth — $details[4]) / 2; // this will return the x coordinate centered to your specific image. Make sure you set $imgwidth to the width of the image you are using.
imagettftext($image, $fontsize, 0, $xcoord, $ycoord, $fontcolor, $font, $ip);
i’ve found a work around for this situation
it seems that height is directly proportional to line spacing so you just have to apply the same factor to image height
$spacing = 0.7;
$params = array(«linespacing» => $spacing);
$box = imageftbbox ($size, 0, $font, $text, $params);
$tw=$box[4]-$box[0]; //image width
$th=($box[1]-$box[5])*$spacing; //image height
This function can be used to generate right-aligned text. Just work out how wide the text image is and position it accordingly. Example:
$i_w >$i_height = 40;
$string = «Hello World!»;
$pointsize = 10;
$fontfile = «/usr/local/lib/ttf/Helve.ttf»;
$im = imagecreate($i_width, $i_height);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);
$string_size = ImageFtBbox($pointsize, 0, $fontfile, $string, array(«linespacing» => 1));
$s_w >$s_height = $string_size[5];
ImageFtText($im, $pointsize, 0, $i_width — $s_width — 1, 0 — $s_height, $white, $fontfile, $string, array(«linespacing» => 1));
Header («Content-type: image/png»);
ImagePNG ($im);
ImageDestroy ($im);
I noticed that PHP’s True Type functions do not allow you to create text blocks with multiple lines that automatically adjust for alignment. I wrote a function that will allow you to generate images with multiple lines, control the alignment, and handle rotation. I hope it helps someone.
There was too much code to paste on this message post so you can grab it off of my webserver. I also created an example page so that you can see the code in action.
Download the Text file:
http://www.PrintsMadeEasy.com /code_samples/php/text_generation.txt
For alignment i used this method:
if($align == «center» || $align == «right»)
<
$verticaltxtspace = $backwidth — (2 * $posx);
$spacepositions = imagettfbbox($size, $angle, «fonts/verdanaz.ttf», » «);
$spacepx = $spacepositions[4] — $spacepositions[0];
// Split text in lines
$lines = split(«[\r][\n]», $text);
for($count = 0; $count
Наложение текста на изображение по центру на php
Наложение текста на картинку при помощи php не такая уж и сложная задача, главное разобраться с функцией imagettftext(), которая имеет ряд параметров:
Описание
imagettftext(‘Фон или фотка’, ‘Размер шрифта’, ‘Угол наклона’, ‘Координат оп оси X’, ‘Координат оп оси Y’, ‘Цвет шрифта’, ‘Путь к файлу со шрифтом’, ‘Любой текст’)
- Фон или фотка = imagecreatefromjpeg(«images/img.jpg») — (в нашем случае это изображение)
- Размер шрифта = 22 — 22px
- Угол наклона = 30 — 30 градусов наклон надписи
- Координат оп оси Y = 200 — 200 пикселей отступ сверху
- Координат оп оси X = 100 — 100 пикселей отступ слева
- Цвет шрифта = imageColorAllocate(‘Фон или фотка’, 255, 255, 255) — возвращает идентификатор цвета, представляющий цвет, составленный из данных RGB-компонентов.
- Путь к файлу со шрифтом = «fonts_capcha/tahoma.ttf» — тут все понятно
- Любой текст = ‘Тект который мы будем накладывать на фотку’
Код php наложения текста
Наложение текста по центру исходной картинки, то есть если вы подставите свой фон для наложения текста, то он все ровно будет расположен по центру. Так же мы добавили в код обводку на текст, для того что бы на светлых тонах фонового ихзображения, текст все ровно выделялся и удобно читался пользователем.
Обводка на текст при помощи php создается очень просто — нужно всего лишь создать такие же текста функцией imagettftext(), но на 1,2 пикселя смещая координаты.
Наложение текста по центру
imagettfbbox() возвращает массив из 8 элементов, представляющих 4 точки, образующие бокс текста:
0- | нижний левый угол, X-позиция |
1- | нижний левый угол, Y-позиция |
2- | нижний правый угол, X-позиция |
3- | нижний правый угол, Y-позиция |
4- | верхний правый угол, X-позиция |
5- | верхний правый угол, Y-позиция |
6- | верхний левый угол, X-позиция |
7- | верхний левый угол, Y-позиция |
Разметка на html
Разметку мы делаем для наглядного примера и удобного теста.