Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
En este artículo, aprenderá cómo convertir un SVG a JPG usando Aspose.HTML for Java y cómo aplicar
ImageSaveOptions. Puede utilizar fácilmente ejemplos de Java para convertir SVG a JPG, que se detallan aquí para convertir
SVG a PNG, imágenes BMP, GIF y TIFF. ¡Simplemente configure el ImageFormat requerido en ImageSaveOptions!
La conversión de SVG a cualquier formato de imagen compatible sigue los pasos obligatorios:
Para especificar el formato de la imagen de salida, utilice la clase
ImageSaveOptions. El constructor ImageSaveOptions(format) inicializa el objeto de opciones con el formato especificado. Puede configurar el formato de imagen en JPG, PNG, BMP, TIFF y GIF. El ImageFormat predeterminado es PNG.
La conversión de SVG a JPG le brinda una imagen rasterizada que se puede compartir, ver o enviar por correo electrónico fácilmente. Los métodos estáticos de la clase Converter se utilizan principalmente como la forma más sencilla de convertir un código SVG a varios formatos. ¡Puedes convertir SVG a JPG en tu aplicación Java literalmente con unas pocas líneas de código!
En el ejemplo, usamos el método convertSVG(content, baseUri, options, outputPath) de la clase
Converter que toma cuatro parámetros: cadena con el código SVG que se va a convertir, la carpeta base para el archivo SVG de entrada , una instancia de la clase ImageSaveOptions y la ruta del archivo de salida donde se guardará la imagen convertida:
1// Convert SVG to JPG in a few lines using Java
2
3// Prepare SVG code
4String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
5 "<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
6 "</svg>\n";
7
8// Invoke the convertSVG() method to convert SVG to image
9Converter.convertSVG(code, ".", new ImageSaveOptions(ImageFormat.Jpeg), "output.jpg");Los archivos SVG son excelentes para gráficos de sitios web, pero no todos los navegadores web los admiten. La conversión de SVG a JPG garantiza que la imagen se cargará correctamente en cualquier navegador web, lo que permitirá una mejor experiencia de usuario. Además, las imágenes JPG son fáciles de compartir, enviar por correo electrónico, incrustar en informes o presentaciones, etc. En el siguiente ejemplo de Java, recorreremos las instrucciones paso a paso para convertir SVG a JPG con opciones de guardado predeterminadas:
convertSVG() de la clase
Converter para guardar SVG como una imagen JPG. En el ejemplo, utilizamos el método
convertSVG(document, options, outputPath).El siguiente fragmento de código Java muestra cómo convertir SVG a JPG usando Aspose.HTML for Java:
1// Convert SVG to JPG using Java
2
3// Prepare SVG code and save it to a file
4String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
5 "<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
6 "</svg>\n";
7try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
8 fileWriter.write(code);
9}
10
11// Initialize an SVG document from the SVG file
12SVGDocument document = new SVGDocument("document.svg");
13
14// Initialize ImageSaveOptions
15ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
16
17// Convert SVG to JPG
18Converter.convertSVG(document, options, "output.jpg");La clase ImageSaveOptions proporciona métodos que le brindan control total sobre una amplia gama de parámetros y mejoran el proceso de conversión de SVG a formatos de archivo de imagen. Puede especificar el formato de imagen, tamaño de página, márgenes, nivel de compresión, tipo de medio, etc.
| Method | Description |
|---|---|
| setCompression(value) | Sets the Tagged Image File Format (TIFF) Compression. By default this property is Compression.LZW. |
| getCss | Gets a CssOptions object which is used for configuration of CSS properties processing. |
| setFormat(value) | Sets ImageFormat (JPG, PNG, BMP, TIFF, or GIF). By default this property is ImageFormat.Png. |
| setBackgroundColor(value) | Sets Color which will fill background of every page. Default value is Color.Transparent(Color.getTransparent()). |
| setPageSetup(value) | Gets a page setup object is used for configuration output page-set. |
| setHorizontalResolution(value) | Sets horizontal resolution for output images in pixels per inch. The default value is 300 dpi. |
| setVerticalResolution(value) | Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi. |
| setSmoothingMode(value) | Sets the rendering quality for this image. |
| getText() | Gets a TextOptions object which is used for configuration of text rendering. |
Puede descargar los ejemplos completos y los archivos de datos desde GitHub.
Para obtener más información sobre ImageSaveOptions, lea el artículo Convertidores de ajuste fino.
Si su escenario requiere renderizar un documento SVG, por ejemplo, en formato de archivo JPG con opciones de guardado personalizadas, el siguiente ejemplo demuestra lo simple que es esto:
Page para configurar la página de salida.setBackgroundColor() para establecer el color de fondo de cada página.setSmoothingMode() para establecer la calidad del suavizado de la imagen en alta.sourcePath, options, outputPath) de la clase
Converter para guardar SVG como una imagen JPG. 1// Convert SVG to JPG in Java with custom settings
2
3// Prepare SVG code and save it to a file
4String code =
5 "<svg width='450' height='450' xmlns='http://www.w3.org/2000/svg'>" +
6 " <g fill='RoyalBlue'>" +
7 " <rect x='100' y='100' rx='25' ry='25' width='200' height='56' />" +
8 " <rect x='100' y='100' rx='25' ry='25' width='200' height='56' transform ='rotate(90 200 128)' />" +
9 " <rect x='100' y='100' rx='25' ry='25' width='200' height='56' transform ='rotate(-45 200 128)' />" +
10 " <rect x='100' y='100' rx='25' ry='25' width='200' height='56' transform ='rotate(45 200 128)' />" +
11 " </g>" +
12 " <circle cx='200' cy='128' r='28' stroke='pink' stroke-width='50' stroke-dasharray='3 13' fill='Orange' />" +
13 " <circle cx='200' cy='128' r='5' />" +
14 "</svg>";
15
16try (java.io.FileWriter fileWriter = new java.io.FileWriter("flower.svg")) {
17 fileWriter.write(code);
18}
19
20// Initialize ImageSaveOptions and set up smoothing mode, page size, and background color
21ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
22PageSetup pageSetup = new PageSetup();
23options.setSmoothingMode(SmoothingMode.HighQuality);
24Page anyPage = new Page();
25anyPage.setSize(new Size(Length.fromPixels(200), Length.fromPixels(200)));
26pageSetup.setAnyPage(anyPage);
27options.setPageSetup(pageSetup);
28options.setBackgroundColor(Color.getAliceBlue());
29
30// Call the convertSVG() method to convert the "flower.svg" file to a JPEG image
31Converter.convertSVG("flower.svg", options, "flower.jpg");Verifique la calidad de la conversión de SVG a JPG con nuestro [Convertidor de SVG a JPG] en línea (23). Sube, convierte tus archivos y obtén el resultado en unos segundos. ¡Pruebe nuestro potente conversor de SVG a JPG gratis ahora!
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.