MCPcopy Create free account
hub / github.com/LibPDF-js/core / parseJpegHeader

Function parseJpegHeader

src/images/jpeg.ts:66–160  ·  view source on GitHub ↗
(bytes: Uint8Array)

Source from the content-addressed store, hash-verified

64 * @throws {Error} If not a valid JPEG or header is malformed
65 */
66export function parseJpegHeader(bytes: Uint8Array): JpegInfo {
67 if (bytes.length < 2) {
68 throw new Error("Invalid JPEG: too short");
69 }
70
71 // Check for JPEG magic bytes
72 if (bytes[0] !== 0xff || bytes[1] !== MARKER_SOI) {
73 throw new Error("Invalid JPEG: missing SOI marker");
74 }
75
76 let offset = 2;
77
78 while (offset < bytes.length - 1) {
79 // Find next marker
80 if (bytes[offset] !== 0xff) {
81 throw new Error(`Invalid JPEG: expected marker at offset ${offset}`);
82 }
83
84 // Skip padding bytes (0xff 0xff ...)
85 while (offset < bytes.length && bytes[offset] === 0xff) {
86 offset++;
87 }
88
89 if (offset >= bytes.length) {
90 throw new Error("Invalid JPEG: unexpected end of file");
91 }
92
93 const marker = bytes[offset];
94 offset++;
95
96 // Check for SOF marker
97 if (isSOFMarker(marker)) {
98 if (offset + 7 > bytes.length) {
99 throw new Error("Invalid JPEG: SOF segment too short");
100 }
101
102 // Skip segment length (2 bytes)
103 // const segmentLength = (bytes[offset] << 8) | bytes[offset + 1];
104
105 const bitsPerComponent = bytes[offset + 2];
106 const height = (bytes[offset + 3] << 8) | bytes[offset + 4];
107 const width = (bytes[offset + 5] << 8) | bytes[offset + 6];
108 const numComponents = bytes[offset + 7];
109
110 // Determine color space from number of components
111 let colorSpace: "DeviceGray" | "DeviceRGB" | "DeviceCMYK";
112
113 switch (numComponents) {
114 case 1:
115 colorSpace = "DeviceGray";
116 break;
117 case 3:
118 colorSpace = "DeviceRGB";
119 break;
120 case 4:
121 colorSpace = "DeviceCMYK";
122 break;
123 default:

Callers 2

embedJpegMethod · 0.90
jpeg.test.tsFile · 0.90

Calls 1

isSOFMarkerFunction · 0.85

Tested by

no test coverage detected