Script JSP (RTF.jsp)
Vamos a detallar someramente el Script correspondiente a RTF empezando por las importaciones.
<%@ page import="java.lang.*" %> <%@ page import="java.io.*" %> <%!
Header indicador de que es un srchivo RTF, con tipo de definición de idioma.
String sRTF = "{\\rtf1"//Indicador RTF +"\\ansi\\ansicpg1252"//1252->Western European +"\\deff0\\deflang9226 \n";//9226->Español Colombia
Definiciones de cadenas para definir nuevo parágrafo, nueva página y nueva línea.
String sNParag = "\\par ";//Nuevo Parágrafo String sNPagina = "\n\\page \\par \n";//Nueva Página String sNLinea = "\n\\line";//Nueva Línea
Definiciones de Fuentes. Aunque se puede configurar sin necesidad de establecer una enumeración, esto lo hice por comodidad e incluí un salto de línea “\n” en el archivo RTF generado, más no en su presentación.
Podemos establecer las fuentes que deseemos utilizar.
String[] sFFam = {"\n", " {\\f1\\fnil\\fprq1\\fcharset0 TlwgMono;}\n", " {\\f2\\fswiss\\fprq1\\fcharset0 Arial;}\n", " {\\f3\\froman\\fprq1\\fcharset0 Times New Roman;}\n", " {\\f4\\fmodern\\fprq1\\fcharset0 Courier New;}\n", " {\\f5\\fscript\\fprq1\\fcharset0 Edwardian Script ITC;}\n"}; //Familia de Fuentes String sTablaF = "\n{\\fonttbl\n"+sFFam[0]+sFFam[1] +sFFam[2]+sFFam[3]+sFFam[4]+sFFam[5]+"}\n";//Tabla de Fuentes
De igual manera se define la tabla de colores que se utilizaría en nuestro RTF
String[] sFCol = { " \\red0\\green0\\blue0;\n", //Negro " \\red0\\green0\\blue255;\n", //Azul " \\red0\\green255\\blue255;\n", //Cian " \\red0\\green255\\blue0;\n", //Verde " \\red255\\green0\\blue255;\n", //Magenta " \\red255\\green0\\blue0;\n", //Red " \\red255\\green255\\blue0;\n", //Amarillo " \\red255\\green255\\blue255;\n" //Blanco }; //Color de Fuentes String sTablaC = "\n{\\colortbl;\n"+sFCol[0]+sFCol[1]+sFCol[2]+sFCol[3]+ sFCol[4]+sFCol[5]+sFCol[6]+sFCol[7]+"}\n";//Tabla de Colores
Por último definimos el Header en su totalidad de nuestro RTF y el Footer (fin de RTF)
String sHeader = sRTF+sTablaF+sTablaC; String sFooter = "}";
Script PHP (RTF.php)
La contraparte de PHP del código anterior:
<?php $sRTF = "{\\rtf1"//Indicador RTF ."\\ansi\\ansicpg1252"//1252->Western European ."\\deff0\\deflang9226 \n";//9226->Español Colombia $sNParag = "\\par ";//Nuevo Parágrafo $sNPagina = "\n\\page \\par \n";//Nueva Página $sNLinea = "\n\\line";//Nueva Línea $sFFam = array("\n", " {\\f1\\fnil\\fprq1\\fcharset0 TlwgMono;}\n", " {\\f2\\fswiss\\fprq1\\fcharset0 Arial;}\n", " {\\f3\\froman\\fprq1\\fcharset0 Times New Roman;}\n", " {\\f4\\fmodern\\fprq1\\fcharset0 Courier New;}\n", " {\\f5\\fscript\\fprq1\\fcharset0 Edwardian Script ITC;}\n"); //Familia de Fuentes $sTablaF = "\n{\\fonttbl\n".$sFFam[0].$sFFam[1] .$sFFam[2].$sFFam[3].$sFFam[4].$sFFam[5]."}\n";//Tabla de Fuentes $sFCol = array( " \\red0\\green0\\blue0;\n", //Negro " \\red0\\green0\\blue255;\n", //Azul " \\red0\\green255\\blue255;\n", //Cian " \\red0\\green255\\blue0;\n", //Verde " \\red255\\green0\\blue255;\n", //Magenta " \\red255\\green0\\blue0;\n", //Red " \\red255\\green255\\blue0;\n", //Amarillo " \\red255\\green255\\blue255;\n" //Blanco ); //Color de Fuentes $sTablaC = "\n{\\colortbl;\n".$sFCol[0].$sFCol[1].$sFCol[2].$sFCol[3]. $sFCol[4].$sFCol[5].$sFCol[6].$sFCol[7]."}\n";//Tabla de Colores $sHeader = $sRTF.$sTablaF.$sTablaC; $sFooter = "}";
Ahora definiremos algunos formatos básicos y necesarios para la presentación de Texto y de Texto en Celdas de Tabla.
Primero los bordes de Tabla y/o de Celda.
$aBorde = array( '\\brdrnone', //No border. '\\brdrs', //Single-thickness border. '\\brdrth', //Double-thickness border. '\\brdrsh', //Shadowed border. '\\brdrdb', //Double border. '\\brdrdot', // Dotted border. '\\brdrdash', //Dashed border. '\\brdrinset', //Inset border. '\\brdroutset' //Outset border. );//Arreglo de Tipos de Borde
Alineación de texto
$aAlign = array( "",// Dejar Igual "\\qc",// Centrar "\\ql",// Izquierda "\\qr",// Derecha "\\qj",// Justificar "\\qd" // Distribuir );//Tipo De Alineación Horizontal de Texto
Alineación Horizontal de Tabla
$aAliHT = array( '\\trqc', //Centers a table row with respect to its containing column. '\\trql', //Left-justifies a table row with respect to its containing column. '\\trqr' //Right-justifies a table row with respect to its containing column. );//Tipo De Alineación Horizontal de Tabla
Alineación Vertical de texto en celda
$aAliVC = array( "\\clvertalt", //Text is top-aligned in cell (the default). "\\clvertalc", //Text is centered vertically in cell. "\\clvertalb" //Text is bottom-aligned in cell. );//Tipo De Alineación Vertical de Celda
Mezcla de celdas verticalmente en una tabla
$aUneVC = array( "", //Ninguna Mezcla. "\\clvmgf", //The first cell in a range of table cells to be vertically merged "\\clvmrg" //Contents of the table cell are vertically merged with those of the preceding cell );//Tipo De Unión Vertical de Celda
Script JSP (RTF.jsp)
Ya se detalló con anterioridad unas definiones que se utilizarán en las diferentes funciones o métodos del Archivo RTF.jsp o RTF.php.
String[] aBorde = { "\\brdrnone", //No border. "\\brdrs", //Single-thickness border. "\\brdrth", //Double-thickness border. "\\brdrsh", //Shadowed border. "\\brdrdb", //Double border. "\\brdrdot", // Dotted border. "\\brdrdash", //Dashed border. "\\brdrinset", //Inset border. "\\brdroutset" //Outset border. };//Arreglo de Tipos de Borde String[] aAlign = { "",// Dejar Igual "\\qc",// Centrar "\\ql",// Izquierda "\\qr",// Derecha "\\qj",// Justificar "\\qd" // Distribuir };//Tipo De Alineación Horizontal de Texto String[] aAliHT = { "\\trqc", //Centers a table row with respect to its containing column. "\\trql", //Left-justifies a table row with respect to its containing column. "\\trqr" //Right-justifies a table row with respect to its containing column. };//Tipo De Alineación Horizontal de Tabla String[] aAliVC = { "\\clvertalt", //Text is top-aligned in cell (the default). "\\clvertalc", //Text is centered vertically in cell. "\\clvertalb" //Text is bottom-aligned in cell. };//Tipo De Alineación Vertical de Celda String[] aUneVC = { "", //Ninguna Mezcla. "\\clvmgf", //The first cell in a range of table cells to be vertically merged "\\clvmrg" //Contents of the table cell are vertically merged with those of the preceding cell };//Tipo De Unión Vertical de Celda
Ahora detallamos unas funciones que nos permiten la creación de tablas y celdas.
String sTablIH(int EspMd, int Posic, int AligH, int Borde,int Grosr,int Color) { //Inicio de Cabecera de Tabla; //\trowd Sets table row defaults. //\trgaphN Half the space between the cells of a table row in twips. String sEspMd = "\\trgaph"+String.valueOf(EspMd);//Espacio medio en twips entre celdas de una fila //\trleftN Position in twips of the leftmost edge of the table with respect to the left edge of its column. String sPosic = "\\trleft"+String.valueOf(Posic);// //\trhdr Table row header. This row should appear at the top of every page on which the current table appears. String sHdT = "\n\\ltrrow\\trowd"+sEspMd+sPosic+aAliHT[AligH];//Cabecera de la Tabla //TipoDeBorde String sBorde = Borde==0?"":aBorde[Borde];//Tipo de Borde sHdT = Borde==0?sHdT+" \n":sHdT+"\\trhdr \n"; //GrosorDeBorde String sGrosr = Grosr==0?"":"\\brdrw"+String.valueOf(Grosr);//Grosor en twips del borde, debe ser <= 255. //ColorDeBorde String sColor = Color==0?"":"\\brdrcf"+String.valueOf(Color);//Color del borde, según tabla de colores. //BordesDeTabla String sTop = "\\trbrdrt"+sBorde+sGrosr+sColor+" ";//Table row border top String sBot = "\\trbrdrb"+sBorde+sGrosr+sColor+" ";//Table row border bottom String sLft = "\\trbrdrl"+sBorde+sGrosr+sColor+" ";//Table row border left String sRgt = "\\trbrdrr"+sBorde+sGrosr+sColor+" ";//Table row border right String sHHz = "\\trbrdrh"+sBorde+sGrosr+sColor+" ";//Table row border horizontal (inside). String sHVt = "\\trbrdrv"+sBorde+sGrosr+sColor+" ";//Table row border vertical (inside). String sTablIH = sHdT+sTop+sLft+sBot+sRgt+"\n"+sHHz+sHVt+"\n"; return sTablIH; } String sTablFH() { //Fin de Cabecera de Tabla; String sTablFH = "\n\\pard\\intbl\\pard\\plain \n"; //String sTablFH = "\n\\pard\\intbl\\pard\\plain \n"; return sTablFH; } String sTablIF(int EspMd, int Posic, int AligH) { //Inicio de Fila de Tabla; //\trowd Sets table row defaults. //\trgaphN Half the space between the cells of a table row in twips. String sEspMd = "\\trgaph"+String.valueOf(EspMd);//Espacio medio en twips entre celdas de una fila //\trleftN Position in twips of the leftmost edge of the table with respect to the left edge of its column. String sPosic = "\\trleft"+String.valueOf(Posic);// String sTablIF = "\n\\row\\pard\n\\trowd"+sEspMd+sPosic+aAliHT[AligH]+" \n";//Fila de la Tabla return sTablIF; } String sTablFF() { //Fin de Fila de Tabla; String sTablFF = "\n\\row\\pard \n"; return sTablFF; } String sCeldaH(int Ancho, int Mezcla, int AligV, int Borde,int Grosr,int Color) { //\[MezclaVertical]\[AlineacionVertical]\TipoDeBorde\GrosorDeBorde\ColorDeBorde //TipoDeBorde String sBorde = Borde==0?"":aBorde[Borde];//Tipo de Borde //GrosorDeBorde String sGrosr = Grosr==0?"":"\\brdrw"+String.valueOf(Grosr);//Grosor en twips del borde, debe ser <= 255. //ColorDeBorde String sColor = Color==0?"":"\\brdrcf"+String.valueOf(Color);//Color del borde, según tabla de colores. //BordesDeCelda String sTop = "\\clbrdrt"+sBorde+sGrosr+sColor+" ";//Top table cell border String sBot = "\\clbrdrb"+sBorde+sGrosr+sColor+" ";//Bottom table cell border String sLft = "\\clbrdrl"+sBorde+sGrosr+sColor+" ";//Left row border left String sRgt = "\\clbrdrr"+sBorde+sGrosr+sColor+" ";//Right table cell border //\cellxN Defines the right boundary of a table cell, including its half of the space between cells. String sLimit = "\\cellx"+Ancho+" \n"; String sCeldaH = aUneVC[Mezcla]+aAliVC[AligV]+sTop+sLft+sBot+sRgt+sLimit; return sCeldaH; }
sTablIH nos permite definir el inicio de la cabecera de la tabla, con sus formatos. El código como tal está documentado.
sTablFH indica el fin de la cabecera de la tabla.
sTablIF indica inicio de definición de fila.
sTablFF indica fin de definición de fila.
sCeldaH permite establecer la definición de celda, formato de bordes, etc.
Script PHP (RTF.php)
De igual forma se definieron las funciones para PHP. Se debe tener en cuenta que las enumeraciones en cada función donde se necesitan se deben declarar como global.
function sTablIH($EspMd,$Posic,$AligH,$Borde,$Grosr,$Color) { //Inicio de Cabecera de Tabla; //\trowd Sets table row defaults. //\trgaphN Half the space between the cells of a table row in twips. $sEspMd = "\\trgaph".$EspMd;//Espacio medio en twips entre celdas de una fila //\trleftN Position in twips of the leftmost edge of the table with respect to the left edge of its column. $sPosic = "\\trleft".$Posic;// //\trhdr Table row header. This row should appear at the top of every page on which the current table appears. global $aAliHT; $sHdT = "\n\\ltrrow\\trowd".$sEspMd.$sPosic.$aAliHT[$AligH];//Cabecera de la Tabla //TipoDeBorde global $aBorde; $sBorde = ($Borde==0)?"":$aBorde[$Borde];//Tipo de Borde $sHdT = ($Borde==0)?$sHdT." \n":$sHdT."\\trhdr \n"; //GrosorDeBorde $sGrosr = ($Grosr==0)?"":"\\brdrw".$Grosr;//Grosor en twips del borde, debe ser <= 255. //ColorDeBorde $sColor = ($Color==0)?"":"\\brdrcf".$Color;//Color del borde, según tabla de colores. //BordesDeTabla $sTop = "\\trbrdrt".$sBorde.$sGrosr.$sColor." ";//Table row border top $sBot = "\\trbrdrb".$sBorde.$sGrosr.$sColor." ";//Table row border bottom $sLft = "\\trbrdrl".$sBorde.$sGrosr.$sColor." ";//Table row border left $sRgt = "\\trbrdrr".$sBorde.$sGrosr.$sColor." ";//Table row border right $sHHz = "\\trbrdrh".$sBorde.$sGrosr.$sColor." ";//Table row border horizontal (inside). $sHVt = "\\trbrdrv".$sBorde.$sGrosr.$sColor." ";//Table row border vertical (inside). $sTablIH = $sHdT.$sTop.$sLft.$sBot.$sRgt."\n".$sHHz.$sHVt."\n"; return $sTablIH; } function sTablFH() { //Fin de Cabecera de Tabla; $sTablFH = "\n\\pard\\intbl\\pard\\plain \n"; return $sTablFH; } function sTablIF($EspMd,$Posic,$AligH) { //Inicio de Fila de Tabla; //\trowd Sets table row defaults. //\trgaphN Half the space between the cells of a table row in twips. $sEspMd = "\\trgaph".$EspMd;//Espacio medio en twips entre celdas de una fila //\trleftN Position in twips of the leftmost edge of the table with respect to the left edge of its column. $sPosic = "\\trleft".$Posic;// global $aAliHT; $sTablIF = "\n\\row\\pard\n\\trowd".$sEspMd.$sPosic.$aAliHT[$AligH]." \n";//Fila de la Tabla return $sTablIF; } function sTablFF() { //Fin de Fila de Tabla; $sTablFF = "\n\\row\\pard \n"; return $sTablFF; } function sCeldaH($Ancho,$Mezcla,$AligV,$Borde,$Grosr,$Color) { //\[MezclaVertical]\[AlineacionVertical]\TipoDeBorde\GrosorDeBorde\ColorDeBorde //TipoDeBorde global $aBorde; $sBorde = ($Borde==0)?"":$aBorde[$Borde];//Tipo de Borde //GrosorDeBorde $sGrosr = ($Grosr==0)?"":"\\brdrw".$Grosr;//Grosor en twips del borde, debe ser <= 255. //ColorDeBorde $sColor = ($Color==0)?"":"\\brdrcf".$Color;//Color del borde, según tabla de colores. //BordesDeCelda $sTop = "\\clbrdrt".$sBorde.$sGrosr.$sColor." ";//Top table cell border $sBot = "\\clbrdrb".$sBorde.$sGrosr.$sColor." ";//Bottom table cell border $sLft = "\\clbrdrl".$sBorde.$sGrosr.$sColor." ";//Left row border left $sRgt = "\\clbrdrr".$sBorde.$sGrosr.$sColor." ";//Right table cell border //\cellxN Defines the right boundary of a table cell, including its half of the space between cells. $sLimit = "\\cellx".$Ancho." \n"; global $aUneVC; global $aAliVC; $sCeldaH = $aUneVC[$Mezcla].$aAliVC[$AligV].$sTop.$sLft.$sBot.$sRgt.$sLimit; return $sCeldaH; }
Ahora describimos unas funciones que son importantes para el manejo de texto.
function sFrmtBS($Align,$CFrnt,$CFond,$Fuente,$Talla){ //Formatos Necesarios $sCFrnt = "\\cf".$CFrnt; $sCFond = "\\cb".$CFond; $sFuente = "\\f".$Fuente; $sTalla = "\\fs".(2*$Talla); global $aAlign; $sFrmtBS = $aAlign[$Align].$sCFrnt.$sCFond.$sFuente.$sTalla."\n"; return $sFrmtBS; } function sFrmtSP($Negrt,$Italc,$Sbryd){ //Aplicar o Quitar Formatos Especiales $sNegrt = ($Negrt==0)?"\\b0":"\\b";// Negrita $sItalc = ($Italc==0)?"\\i0":"\\i";// Itálica $sSbryd = ($Sbryd==0)?"\\ul0":"\\ul";// Subrayar $sFrmtSP = $sNegrt.$sItalc.$sSbryd."\n"; return $sFrmtSP; } function sCeldaC($Formato, $Contenido) { $sCeldaC = "\\pard\\plain\\intbl\\ltrpar"; //\cell Denotes the end of a table cell. $sCeldaC = $sCeldaC.$Formato.$Contenido."\\cell \n"; return $sCeldaC; } function sTexto($Formato,$Contenido) { $sTexto = $Formato.$Contenido."\n"; return $sTexto; } function RTFImagen($ImageString,$Tipo,$Alto,$Ancho,$SclY,$SclX, $AltP,$AncP,$CropL,$CropR,$CropT,$CropB){ $RTFImagen = "\n"."{\\pict"; $sLibI = "\\"; switch ($Tipo){ case 1: $sLibI = $sLibI."pngblip"; break; case 2: $sLibI = $sLibI."jpegblip"; break; } $sAlto = "\\pich".$Alto; $sAnch = "\\picw".$Ancho; $sSclX = "\\picscalex".$SclY; $sSclY = "\\picscaley".$SclX; $sAltP = "\\pichgoal".$AltP; $sAncP = "\\picwgoal".$AncP; $sCrpL = "\\piccropl".$CropL; $sCrpR = "\\piccropr".$CropR; $sCrpT = "\\piccropt".$CropT; $sCrpB = "\\piccropb".$CropB; $RTFImagen = $RTFImagen.$sSclX.$sSclY.$sCrpL.$sCrpR.$sCrpT.$sCrpB."\n".$sAnch. $sAlto.$sAncP.$sAltP.$sLibI."\n".$ImageString."\n}\\par"; return $RTFImagen; }
sFrmtBS Permite establecer el formato básico necesario para la presentación de texto.
sFrmtSP Aparte del formato básico necesario, permite cambiar agregando o quitando otro formato opcional.
sCeldaC Permite desplegar el contenido de una celda en una tabla, teniendo en cuenta el formato.
sTexto Permite desplegar un texto requiriéndose su formato respectivo.
RTFImagen Permite incluir una imagen, recibiéndose como parámetros el formato de su presentación.
Script JSP (RTF.jsp)
El código para JSP es muy similar por no decir que es igual.
String sFrmtBS(int Align, int CFrnt, int CFond, int Fuente, int Talla){ //Formatos Necesarios String sCFrnt = "\\cf"+String.valueOf(CFrnt); String sCFond = "\\cb"+String.valueOf(CFond); String sFuente = "\\f"+String.valueOf(Fuente); String sTalla = "\\fs"+String.valueOf(2*Talla); String sFrmtBS = aAlign[Align]+sCFrnt+sCFond+sFuente+sTalla+"\n"; return sFrmtBS; } String sFrmtSP(int Negrt, int Italc, int Sbryd){ //Aplicar o Quitar Formatos Especiales String sNegrt = Negrt==0?"\\b0":"\\b";// Negrita String sItalc = Italc==0?"\\i0":"\\i";// Itálica String sSbryd = Sbryd==0?"\\ul0":"\\ul";// Subrayar String sFrmtSP = sNegrt+sItalc+sSbryd+"\n"; return sFrmtSP; } String sCeldaC(String Formato, String Contenido) { String sCeldaC = "\\pard\\plain\\intbl\\ltrpar"; //\cell Denotes the end of a table cell. sCeldaC = sCeldaC+Formato+Contenido+"\\cell \n"; return sCeldaC; } String sTexto(String Formato, String Contenido) { String sTexto = Formato+Contenido+"\n"; return sTexto; } String RTFImagen(String ImageString,int Tipo,int Alto,int Ancho,int SclY,int SclX, int AltP,int AncP,int CropL,int CropR,int CropT,int CropB){ String RTFImagen = "\n"+"{\\pict"; String sLibI = "\\"; switch (Tipo){ case 1: sLibI = sLibI+"pngblip"; break; case 2: sLibI = sLibI+"jpegblip"; break; } String sAlto = "\\pich"+String.valueOf(Alto); String sAnch = "\\picw"+String.valueOf(Ancho); String sSclX = "\\picscalex"+String.valueOf(SclY); String sSclY = "\\picscaley"+String.valueOf(SclX); String sAltP = "\\pichgoal"+String.valueOf(AltP); String sAncP = "\\picwgoal"+String.valueOf(AncP); String sCrpL = "\\piccropl"+String.valueOf(CropL); String sCrpR = "\\piccropr"+String.valueOf(CropR); String sCrpT = "\\piccropt"+String.valueOf(CropT); String sCrpB = "\\piccropb"+String.valueOf(CropB); RTFImagen = RTFImagen+sSclX+sSclY+sCrpL+sCrpR+sCrpT+sCrpB+"\n"+sAnch+ sAlto+sAncP+sAltP+sLibI+"\n"+ImageString+"\n}\\par"; return RTFImagen; }
Ahora describiremos unas funciones que nos permiten acceder a la información de la imagen y disponer de ella para poder insertarla a algún archivo de formato RTF.
String ByteFileImageString(String NombreImagen,int[] Formato,int[] Alto,int[] Ancho) { byte[] BytesFile = new byte[(int)(new File(NombreImagen).length())]; FileInputStream fis; try { fis = new FileInputStream(NombreImagen); fis.read(BytesFile); fis.close(); } catch (FileNotFoundException fnfe) {System.out.println(fnfe.toString());} catch (EOFException eofe) {System.out.println(eofe.toString());} catch (IOException ioe) {System.out.println(ioe.toString());} String ImageString = ByteStreamImageString(BytesFile,Formato,Alto,Ancho); return ImageString; } String ByteStreamImageString(byte[] ByteStream,int[] Formato,int[] Alto,int[] Ancho) { Alto[0] = 0; Ancho[0] = 0; Formato[0] = -1; String ImageString = "Error"; if ((int)(ByteStream[0]&0xFF)==137 && (int)(ByteStream[1]&0xFF)==80 &&(int)(ByteStream[2]&0xFF)==78){ Formato[0] = 1; //PNG Alto[0] = Byte2PosInt(ByteStream[22],ByteStream[23]); Ancho[0] = Byte2PosInt(ByteStream[18],ByteStream[19]); } if ((int)(ByteStream[0]&0xFF)==255 && (int)(ByteStream[1]&0xFF)==216 &&(int)(ByteStream[2]&0xFF)==255 && (int)(ByteStream[3]&0xFF)==224){ Formato[0] = 2; //JPG int PosJPG = 2; while (PosJPG<ByteStream.length){ if (String.format("%02X%02X", ByteStream[PosJPG+0],ByteStream[PosJPG+1]).equals("FFC0")){ Alto[0] = Byte2PosInt(ByteStream[PosJPG+5],ByteStream[PosJPG+6]); Ancho[0] = Byte2PosInt(ByteStream[PosJPG+7],ByteStream[PosJPG+8]); } PosJPG = PosJPG + 2 +Byte2PosInt(ByteStream[PosJPG+2],ByteStream[PosJPG+3]); } } if (Formato[0] > 0){ ImageString = ""; int Salto = 0; for (int i=0;i < ByteStream.length; i++){ Salto++; ImageString = ImageString + String.format("%02x", ByteStream[i]); if (Salto==64){ ImageString = ImageString + "\n"; Salto = 0; } } } return ImageString; } private Integer Byte2PosInt(byte Byte08, byte Byte00) { return new Integer (((Byte08 & 0xFF) << 8)|((Byte00 & 0xFF) << 0)); } %>
ByteFileImageString Lee un archivo cualquiera en forma binaria, retorna su contenido convertido de Byte a su representación numérica, además si es un formato de imagen retorna su alto y Ancho.
ByteStreamImageString Recibe el contenido de representación numérica de cada Byte, determina si ese contenido corresponde a algún formato válido JPG o PNG, determina además el Alto y ancho.
Byte2PosInt Convierte dos Bytes, según el orden a su valor correspondiente a Entero.
Script PHP (RTF.php)
Finalizamos con el código en PHP de las funciones antes descritas.
function ByteFileImageString($NombreImagen,&$Formato,&$Alto,&$Ancho) { $fis = fopen($NombreImagen, "rb"); if ($fis!=false){ $BytesFile = NULL; while (!feof($fis)){ $BytesFile .= fread($fis, 8192); } fclose($fis); }else { printf("Error: ".$NombreImagen); exit(); } $ImageString = ByteStreamImageString($BytesFile,$Formato,$Alto,$Ancho); return $ImageString; } function ByteStreamImageString($ByteStream,&$Formato,&$Alto,&$Ancho) { $Alto = 0; $Ancho = 0; $Formato = -1; $ImageString = "Error"; if (ord($ByteStream[0])==137 && ord($ByteStream[1])==80 && ord($ByteStream[2])==78){ $Formato = 1; //PNG $Alto = Byte2PosInt($ByteStream[22],$ByteStream[23]); $Ancho = Byte2PosInt($ByteStream[18],$ByteStream[19]); } if (ord($ByteStream[0])==255 && ord($ByteStream[1])==216 && ord($ByteStream[2])==255 && ord($ByteStream[3])==224){ $Formato = 2; //JPG $PosJPG = 2; while ($PosJPG<strlen($ByteStream)){ if (sprintf("%02X%02X", ord($ByteStream[$PosJPG+0]),ord($ByteStream[$PosJPG+1]))=="FFC0"){ $Alto = Byte2PosInt($ByteStream[$PosJPG+5],$ByteStream[$PosJPG+6]); $Ancho = Byte2PosInt($ByteStream[$PosJPG+7],$ByteStream[$PosJPG+8]); } $PosJPG = $PosJPG + 2 +Byte2PosInt($ByteStream[$PosJPG+2],$ByteStream[$PosJPG+3]); } } if ($Formato > 0){ $ImageString = ""; $Salto = 0; for ($i=0;$i < strlen($ByteStream); $i++){ $Salto++; $ImageString = $ImageString.sprintf("%02x", ord($ByteStream[$i])); if ($Salto==64){ $ImageString = $ImageString."\n"; $Salto = 0; } } } return $ImageString; } function Byte2PosInt($Byte08,$Byte00) { return ((ord($Byte08) & 0xFF) << 8)|((ord($Byte00) & 0xFF) << 0); } ?>