Как конвертировать UTF-8 URDU текст в изображение на лету в Php?
اردو کے فونٹ کے مسائل
میرے ویب پیچ کے فونٹ ، براوزر کی وجہ سے بدل جاتے ہیں ، میں اپنے صفحے کو امیج بنا کر براوزر کو دینا چایتا
Я пробовал несколько учебных пособий / примеров и поисков. Я не мог найти решение.
- Совет: (Надеюсь, это сделает чью-то жизнь проще.)
Большая проблема, которую я решил при создании образа, заключалась в использовании Windows Share-Point для сохранения моих файлов.php. Все файлы, которые я сохранял, имели что-то вроде UTF BOM .
Когда я сохранил тот же файл, используя простой блокнот в кодировке UTF-8, началось создание моего изображения в PHP.
- Моя проблема.
У меня есть предложение в URDU (язык, на котором говорят в миллиарде в Южной Азии), скажем, строка - сохраненная в UTF-8, отлично сохраненная в базе данных и показанная в веб-браузерах.
В отличие от английского, буквы урду объединяются, чтобы составить слова. При объединении их видимая форма обрезается - размер или стиль.
Я работаю над этим кодом
<?php
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
//$SourceFile is source of the image file to be watermarked
//$WaterMarkText is the text of the watermark
//$DestinationFile is the destination location where the watermarked images will be placed
//Delete if destinaton file already exists
@unlink($DestinationFile);
//This is the vertical center of the image
$top = getimagesize($SourceFile);
$top = $top[1]/2;
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
//Path to the font file on the server. Do not miss to upload the font file
$font = 'arial.ttf';
//Font sie
$font_size = 36;
//Give a white shadow
$white = imagecolorallocate($image_p, 255, 255, 155);
imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);
//Print in black color
$black = imagecolorallocate($image_p, 0, 0, 0);
imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
?>
<?php
/*
// The text to draw
require('../../../I18N/Arabic.php'); // It converts the left side language to right side
$Arabic = new I18N_Arabic('Glyphs'); //
$font = './DroidNaskh-Bold.ttf';
$text = "جب درخشاں ہوں ستاروں کے چراغ";
$text = $Arabic->utf8Glyphs('جب درخشاں ہوں ستاروں کے چراغ ');
It gave me ﻍﺍﺭچ ےک ںﻭﺭﺎﺘﺳںﻭہ ںﺎﺸﺧﺭﺩ ﺐﺟ , reversing the string ,
*/
$text = "ﻍﺍﺭچ ےک ںﻭﺭﺎﺘﺳںﻭہ ںﺎﺸﺧﺭﺩ ﺐﺟ"; // Problem in joining of Urdu -
// Text
// Sequence of characters reversed in string using utf8Glyphs( ) ;
$SourceFile = 'nature (28).jpg';//Source image
$DestinationFile = 'watermarked/sky.jpg';//Destination path
//Call the function to watermark the image
watermarkImage ($SourceFile, $text, $DestinationFile);
//Display watermarked image if desired
if(file_exists($DestinationFile)){
echo "<img src=\"watermarked/sky.jpg\">";
echo "<p>The image has been watermarked at '".$DestinationFile."'</p>";
}
?>
Мой образ создания на FLY для других, чем UTF-8 работает нормально.
С уважением.
3 ответа
Вам понадобится дополнительная библиотека для выполнения соединения арабских глифов. Проверьте AR-PHP.
Для текста URDU в изображении решение не найдено, в PhP ни одна библиотека не работала, и ни одна арабская или персидская библиотека не помогла. Наконец, я выбрал обходной путь. Используйте HTML5 CANVAS с несколькими строками JS и преобразуйте текст в изображения.
С небольшими изменениями мой предыдущий код дошел до этой стадии, я даже попробовал изменить ISO-8859-1 и попытался использовать его после преобразования строки UTF-8 в объекты HTML.
`<?php
function watermarkImage ($SourceFile, $WaterMarkText, $reverseText, $basicText,
$DestinationFile , $Text, $Text7,$Text8) {
//$SourceFile is the source of the image file to be watermarked
//$WaterMarkText is the text of the watermark
//$DestinationFile is the destination location where the watermarked images will be placed
//Delete if destinaton file already exists
@unlink($DestinationFile);
//This is the vertical center of the image
$top = getimagesize($SourceFile);
$top = $top[1]/2;
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
//Path to the font file on the server. Do not miss to upload the font file
$font = 'C:/Windows/Fonts/Jameel Noori Nastaleeq.ttf';
//Font sie
$font_size = 22; // `
`//Give a white shadow
$white = imagecolorallocate($image_p, 255, 255, 155);
imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);
//Print in black color
$black = imagecolorallocate($image_p, 0, 0, 0);
imagettftext($image_p, $font_size, 0, 8, 33, $black, $font, $WaterMarkText);
imagettftext($image_p, $font_size, 0, 68, 120, $black, $font, $reverseText);
imagettftext($image_p, $font_size, 0, 100, 190, $black, $font, $basicText);
imagettftext($image_p, $font_size, 0, 8, $top, $black, $font, $Text);
imagettftext($image_p, $font_size, 0, 8, $top+62, $black, $font, $Text7);
imagettftext($image_p, $font_size, 0, 8, $top+120, $black, $font, $Text8);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
$text7 = "کر سکتی ہے بے معرکہ جِینے کی تلافی"; // Problem in joining of Urdu -
// Convert UTF-8 string to HTML entities
$text = mb_convert_encoding($text7, 'HTML-ENTITIES',"UTF-8");
// Convert HTML entities into ISO-8859-1
$text8 = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Convert characters > 127 into their hexidecimal equivalents
$out = "";
for($i = 0; $i < strlen($text); $i++) {
$letter = $text[$i];
$num = ord($letter);
if($num>127) {
$out .= "&#$num;";
} else {
$out .= $letter;
}
}
$my_string5 = $my_string6 = "";
function ReverseText ($my_string , $my_string7 ) {
$len6 = strlen($my_string);
$my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY);
for ($x = 0; $x < $len6 ; $x++) {
$yy = $x +1; $y = $len6 -$yy;
$my_string7 .= $my_array [$y] ;
}
return $my_string7;
};
$reverseText = ReverseText ($text , $my_string5 );
$basicText = ReverseText ($reverseText , $my_string6 );
// Text
// Sequence of characters reversed in string using utf8Glyphs( ) ;
$SourceFile = 'bb.jpg';//Source image
$DestinationFile = 'book.jpg';//Destination path
//Call the function to watermark the image
watermarkImage ($SourceFile, $text, $reverseText, $basicText, $DestinationFile, $text , $text7 , $text8);
//Display watermarked image if desired
if(file_exists($DestinationFile)){
echo "<img src=\"book.jpg\">";
echo "<p>The image has been watermarked at '".$DestinationFile."'</p>";
}
?>
`
Простое решение HTML5 с использованием Canvas
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="myCanvas" width="522" height="80" style="display:none;">
</canvas>
<img id="canvasImg" alt="Right click to save me!">
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = "40px Jameel Noori Nastaleeq";
context.fillText("فکر رہتی تھی مجھے جس کی وہ محفل ہے یہی ", 50, 60);
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
</script>
</body>
</html>
Лучшее решение и я закрываю квест
Используйте PHP, HTML5 Canvas и JS для преобразования текста UTF-Urdu в изображение.
Мой PHP-код вызывает простую функцию для многократного использования на одной странице.
echo generateCanvas($newCanvas, 'second', $textColor, $second , '2px', '8px' , $cWIDTH );
И функция, которую я сделал
function generateCanvas($myCanvas, $className, $textColor , $misra , $cLEFT, $cTOP ,$cWIDTH ) {
$output = "";
$output .= "<span class=\"$className\">\n";
$output .= "<canvas id=\"$myCanvas\" style='position: relative; left: $cLEFT; top: $cTOP; ' width='$cWIDTH' height='65'> ";
$output .= "</canvas>\n";
$output .= "<script>\n";
$output .= "var canvas = document.getElementById('$myCanvas');\n";
$output .= "canvas.style.backgroundColor = 'yellow';\n";
$output .= "var cty = canvas.getContext('2d');\n";
$output .= "cty.font = '28px Jameel Noori Nastaleeq';\n";
$output .= "cty.fillStyle = '$textColor';\n";
$output .= "cty.fillText('$misra', 530, 50);\n";
$output .= "</script>\n";
$output .= "</span>\n";
return $output;
}
Я также добавил в свой код файла CSS для вызова шрифта с моего веб-сайта, для локального хоста, код для добавления этих строк.
@font-face {
font-family: 'Jameel Noori Nastaleeq';
src: url('http://localhost/fonts/Jameel%20Noori%20Nastaleeq.ttf') format('truetype');
}
Короче говоря, решение такое:
<canvas id="firstCanvas8" style='position: relative; left: 2; top: 2; ' width='548' height='65'> </canvas>
<script>
var canvas = document.getElementById('firstCanvas8');
var cty = canvas.getContext('2d');
cty.font = '28px Jameel Noori Nastaleeq';
cty.fillStyle = 'red';
cty.fillText('سارے جہاں سے اچھا ہندوستاں ہمارا ', 530, 50);
</script>