OLD | NEW |
| (Empty) |
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 import sys | |
5 import os | |
6 import base64 | |
7 | |
8 PNG_PATH = os.path.join(os.path.dirname(__file__), '../../../third_party/png') | |
9 if PNG_PATH not in sys.path: | |
10 sys.path.append(PNG_PATH) | |
11 | |
12 import png # pylint: disable=F0401 | |
13 | |
14 class PngColor(object): | |
15 """Encapsulates an RGB color retreived from a PngBitmap""" | |
16 | |
17 def __init__(self, r, g, b, a=255): | |
18 self.r = r | |
19 self.g = g | |
20 self.b = b | |
21 self.a = a | |
22 | |
23 def IsEqual(self, expected_color, tolerance=0): | |
24 """Verifies that the color is within a given tolerance of | |
25 the expected color""" | |
26 r_diff = abs(self.r - expected_color.r) | |
27 g_diff = abs(self.g - expected_color.g) | |
28 b_diff = abs(self.b - expected_color.b) | |
29 a_diff = abs(self.a - expected_color.a) | |
30 return (r_diff <= tolerance and g_diff <= tolerance | |
31 and b_diff <= tolerance and a_diff <= tolerance) | |
32 | |
33 def AssertIsRGB(self, r, g, b, tolerance=0): | |
34 assert self.IsEqual(PngColor(r, g, b), tolerance) | |
35 | |
36 def AssertIsRGBA(self, r, g, b, a, tolerance=0): | |
37 assert self.IsEqual(PngColor(r, g, b, a), tolerance) | |
38 | |
39 class PngBitmap(object): | |
40 """Utilities for parsing and inspecting inspecting a PNG""" | |
41 | |
42 def __init__(self, base64_png): | |
43 self._png_data = base64.b64decode(base64_png) | |
44 self._png = png.Reader(bytes=self._png_data) | |
45 rgba8_data = self._png.asRGBA8() | |
46 self._width = rgba8_data[0] | |
47 self._height = rgba8_data[1] | |
48 self._pixels = list(rgba8_data[2]) | |
49 self._metadata = rgba8_data[3] | |
50 | |
51 @property | |
52 def width(self): | |
53 """Width of the snapshot""" | |
54 return self._width | |
55 | |
56 @property | |
57 def height(self): | |
58 """Height of the snapshot""" | |
59 return self._height | |
60 | |
61 def GetPixelColor(self, x, y): | |
62 """Returns a PngColor for the pixel at (x, y)""" | |
63 row = self._pixels[y] | |
64 offset = x * 4 | |
65 return PngColor(row[offset], row[offset+1], row[offset+2], row[offset+3]) | |
66 | |
67 def WriteFile(self, path): | |
68 with open(path, "wb") as f: | |
69 f.write(self._png_data) | |
OLD | NEW |