Skip to content

Commit

Permalink
refactor: Use encode_png to generate PNG bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
edgarrmondragon authored and jboarman committed Apr 7, 2023
1 parent 3ce5c0e commit e3ff663
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 13 deletions.
Binary file removed resources/examples/png/octocat.png
Binary file not shown.
1 change: 1 addition & 0 deletions resvg_py.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ class Resvg:

class RenderedImage:
def as_array(self: RenderedImage) -> ndarray: ...
def as_png(self: RenderedImage) -> bytes: ...
14 changes: 9 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use numpy::ndarray::Array3;
use numpy::{IntoPyArray, PyArray3};
use pyo3::prelude::*;
use pyo3::types::PyBytes;
use resvg::tiny_skia::Pixmap;
use usvg::{Size, Tree, TreeParsing};

Expand Down Expand Up @@ -151,11 +152,14 @@ impl RenderedImage {
.into_pyarray(py))
}

/// TODO(edgarrmondragon): Check if this is can be used instead of as_array.
fn as_png(&self) -> PyResult<Vec<u8>> {
self.pixmap.encode_png().map_err(|e| {
pyo3::exceptions::PyException::new_err(format!("Failed to encode PNG: {}", e))
})
/// Returns the rendered image as bytes in PNG format.
fn as_png(&self, py: Python) -> PyResult<PyObject> {
self.pixmap
.encode_png()
.map(|b| PyBytes::new(py, &b).into())
.map_err(|e| {
pyo3::exceptions::PyException::new_err(format!("Failed to encode PNG: {}", e))
})
}
}

Expand Down
Binary file modified tests/snapshots/test_render/test_render/octocat/output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 1 addition & 8 deletions tests/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@

from __future__ import annotations

import io
import typing as t
from pathlib import Path

import pytest
from PIL import Image

import resvg_py

Expand All @@ -27,9 +25,4 @@ def test_render(snapshot: Snapshot, svg_file: str) -> None:

with Path(svg_file).open("r") as input_file:
rendered = r.render(input_file.read(), 400, 400)
array = rendered.as_array()

with io.BytesIO() as png_file:
im = Image.fromarray(array)
im.save(png_file, format="PNG")
snapshot.assert_match(png_file.getvalue(), "output.png")
snapshot.assert_match(rendered.as_png(), "output.png")

0 comments on commit e3ff663

Please sign in to comment.