TODO JPEG Specification 112
333059
private void init() {
        generalHuffsize();
        generalHuffcode();

        int i = 0, j = 0;
        for (;;) {
            i++;

            if (i > 16) {
                break;
            }

            if (L[i] == 0) {
                maxcode[i] = -1;
                continue;
            } else {
                valptr[i] = j;
                mincode[i] = huffcode[j];
                j = j + L[i] - 1;
                maxcode[i] = huffcode[j];
                j++;
            }
        }

        maxcode[17] = 0xFFFFFF;
    }
472169
public static void convertToBoof(Picture input, ImageBase output) {
		if( input.getColor() == ColorSpace.RGB ) {
			ImplConvertJCodecPicture.RGB_to_PLU8(input, (Planar) output);
		} else if( input.getColor() == ColorSpace.YUV420 ) {
			if( output instanceof Planar) {
				Planar ms = (Planar)output;
				if( ms.getImageType().getDataType() == ImageDataType.U8 ) {
					ImplConvertJCodecPicture.yuv420_to_PlRgb_U8(input, ms);
				} else if( ms.getImageType().getDataType() == ImageDataType.F32 ) {
					ImplConvertJCodecPicture.yuv420_to_PlRgb_F32(input, ms);
				}
			} else if( output instanceof GrayU8) {
				ImplConvertJCodecPicture.yuv420_to_U8(input, (GrayU8) output);
			} else if( output instanceof GrayF32) {
				ImplConvertJCodecPicture.yuv420_to_F32(input, (GrayF32) output);
			} else {
				throw new RuntimeException("Unexpected output image type");
			}
		}
	}
1085245
def parse_buffer_to_jpeg(data):
    

    return [
        Image.open(BytesIO(image_data + b'\xff\xd9'))
        for image_data in data.split(b'\xff\xd9')[:-1] # Last element is obviously empty
    ]
943364
public static String imgToBase64StrWithPrefix(BufferedImage image, String formatName) {
        formatName = formatName != null ? formatName : "jpeg";
        return String.format("data:image/%s;base64,%s", formatName, imgToBase64Str(image, formatName));
    }
179206
@Override
	public void getImageBytes(ByteBuffer buffer) {
		final BufferedImage bi = getImage();
		if (bi != null) {
			buffer.put(ImageUtils.imageToBytes(bi));
		}
	}
36244
function (x0, y0, width, height, c)
    {
        _c = c || _c
        const data = _c.getImageData(x0, y0, width, height)
        const bits = data.data

        const pixels = []
        for (let y = 0; y < height; y += _scale)
        {
            for (let x = 0; x < width; x += _scale)
            {
                const index = x * 4 + y * width * 4
                if (bits[index + 3] === 0)
                {
                    pixels.push(null)
                }
                else
                {
                    const color = Color.rgbToHex(bits[index], bits[index + 1], bits[index + 2])
                    pixels.push(parseInt(color, 16))
                }
            }
        }
        return pixels
    }
523529
private BufferedImage to24Bit3ComponentRGB(int[][] decoded, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length / 3; i++) {
            // Convert to RGB (BGR)
            imageBuffer[i * 3 + 2] = (byte) decoded[0][i];
            imageBuffer[i * 3 + 1] = (byte) decoded[1][i];
            imageBuffer[i * 3] = (byte) decoded[2][i];
        }

        return image;
    }
43507
private void processStream(CameraPinholeBrown intrinsic , SimpleImageSequence<GrayU8> sequence , ImagePanel gui , long pauseMilli) {

		Font font = new Font("Serif", Font.BOLD, 24);

		Se3_F64 fiducialToCamera = new Se3_F64();
		int frameNumber = 0;
		while( sequence.hasNext() ) {
			long before = System.currentTimeMillis();
			GrayU8 input = sequence.next();
			BufferedImage buffered = sequence.getGuiImage();
			try {
				detector.detect(input);
			} catch( RuntimeException e ) {
				System.err.println("BUG!!! saving image to crash_image.png");
				UtilImageIO.saveImage(buffered,"crash_image.png");
				throw e;
			}

			Graphics2D g2 = buffered.createGraphics();

			for (int i = 0; i < detector.totalFound(); i++) {
				detector.getFiducialToCamera(i,fiducialToCamera);
				long id = detector.getId(i);
				double width = detector.getWidth(i);

				VisualizeFiducial.drawCube(fiducialToCamera,intrinsic,width,3,g2);
				VisualizeFiducial.drawLabelCenter(fiducialToCamera,intrinsic,""+id,g2);
			}
			saveResults(frameNumber++);

			if( intrinsicPath == null ) {
				g2.setColor(Color.RED);
				g2.setFont(font);
				g2.drawString("Uncalibrated",10,20);
			}

			gui.setImage(buffered);

			long after = System.currentTimeMillis();
			long time = Math.max(0,pauseMilli-(after-before));
			if( time > 0 ) {
				try { Thread.sleep(time); } catch (InterruptedException ignore) {}
			}
		}
	}
255702
public void saveAsJPEG(File file, int width, int height, float quality) throws IOException, TranscoderException {
    JPEGTranscoder t = new JPEGTranscoder();
    t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(width));
    t.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, new Float(height));
    t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(quality));
    transcode(file, t);
  }
864153
private BufferedImage to8Bit1ComponentGrayScale(int[][] decoded, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length; i++) {
            imageBuffer[i] = (byte) decoded[0][i];
        }

        return image;
    }
291747
function handleImageData(handler, xref, res, image) {
    if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {
      // For natively supported jpegs send them to the main thread for decoding.
      var dict = image.dict;
      var colorSpace = dict.get('ColorSpace', 'CS');
      colorSpace = ColorSpace.parse(colorSpace, xref, res);
      var numComps = colorSpace.numComps;
      var decodePromise = handler.sendWithPromise('JpegDecode',
                                                  [image.getIR(), numComps]);
      return decodePromise.then(function (message) {
        var data = message.data;
        return new Stream(data, 0, data.length, image.dict);
      });
    } else {
      return Promise.resolve(image);
    }
  }
5911
function imagebmp(&$im, $filename = "") {

        if (!$im) return false;
        $w = imagesx($im);
        $h = imagesy($im);
        $result = '';

        // if the image is not true color, we convert it first
        if (!imageistruecolor($im)) {
            $tmp = imagecreatetruecolor($w, $h);
            imagecopy($tmp, $im, 0, 0, 0, 0, $w, $h);
            imagedestroy($im);
            $im = & $tmp;
        }

        $biBPLine = $w * 3;
        $biStride = ($biBPLine + 3) & ~3;
        $biSizeImage = $biStride * $h;
        $bfOffBits = 54;
        $bfSize = $bfOffBits + $biSizeImage;

        $result .= substr('BM', 0, 2);
        $result .=  pack ('VvvV', $bfSize, 0, 0, $bfOffBits);
        $result .= pack ('VVVvvVVVVVV', 40, $w, $h, 1, 24, 0, $biSizeImage, 0, 0, 0, 0);

        $numpad = $biStride - $biBPLine;
        for ($y = $h - 1; $y >= 0; --$y) {
            for ($x = 0; $x < $w; ++$x) {
                $col = imagecolorat ($im, $x, $y);
                $result .=  substr(pack ('V', $col), 0, 3);
            }
            for ($i = 0; $i < $numpad; ++$i)
                $result .= pack ('C', 0);
        }

        if($filename==""){
            echo $result;
        } else {
            $file = fopen($filename, "wb");
            fwrite($file, $result);
            fclose($file);
        }
        return true;
    }
405902
function _imageCopyResampledWorkaround(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
    {
        /*
        for ($i = 0; $i < imagecolorstotal($src_img); $i++)
        {
            $colors = ImageColorsForIndex ($src_img, $i);
            ImageColorAllocate ($dst_img, $colors['red'],$colors['green'], $colors['blue']);
        }
        */
        $scaleX = ($src_w - 1) / $dst_w;
        $scaleY = ($src_h - 1) / $dst_h;

        $scaleX2 = $scaleX / 2.0;
        $scaleY2 = $scaleY / 2.0;

        for ($j = $src_y; $j < $src_y + $dst_h; $j++)
        {
            $sY = $j * $scaleY;
            for ($i = $src_x; $i < $src_x + $dst_w; $i++)
            {
                $sX = $i * $scaleX;

                $c1 = ImageColorsForIndex($src_img, ImageColorAt($src_img, (int)$sX, (int)$sY + $scaleY2));
                $c2 = ImageColorsForIndex($src_img, ImageColorAt($src_img, (int)$sX, (int)$sY));
                $c3 = ImageColorsForIndex($src_img, ImageColorAt($src_img, (int)$sX + $scaleX2, (int)$sY + $scaleY2));
                $c4 = ImageColorsForIndex($src_img, ImageColorAt($src_img, (int)$sX + $scaleX2, (int)$sY));

                $red = (integer)(($c1['red'] + $c2['red'] + $c3['red'] + $c4['red']) / 4);
                $green = (integer)(($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) / 4);
                $blue = (integer)(($c1['blue'] + $c2['blue'] + $c3['blue'] + $c4['blue']) / 4);

                $color = ImageColorClosest($dst_img, $red, $green, $blue);
                ImageSetPixel($dst_img, $dst_x + $i - $src_x, $dst_y + $j - $src_y, $color);
            }
        }
    }
364676
public void createImages() {
		image = UtilImageIO.loadImage(UtilIO.pathExample("standard/barbara.jpg"));

		gray = ConvertBufferedImage.convertFromSingle(image, null, GrayU8.class);
		derivX = GeneralizedImageOps.createSingleBand(GrayS16.class, gray.getWidth(), gray.getHeight());
		derivY = GeneralizedImageOps.createSingleBand(GrayS16.class, gray.getWidth(), gray.getHeight());

		GImageDerivativeOps.gradient(DerivativeType.SOBEL, gray, derivX, derivY, BorderType.EXTENDED);
	}
308534
def dump(self):
        """"""
        scan_lines = bytearray()
        for y in range(self.height):
            scan_lines.append(0)  # filter type 0 (None)
            scan_lines.extend(
                self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
            )
        # image represented as RGBA tuples, no interlacing
        return SIGNATURE + \
            self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
                                                 self.width, self.height,
                                                 8, 6, 0, 0, 0)) + \
            self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
            self.pack_chunk(b'IEND', b'')
1030057
private byte[] getFlagBytes()
	{
		byte[] b = new byte[numFlagBytes];
		int bytesCopied = 1;
		b[0] = 0;

		if (update)
		{
			b[0] |= 0x80;
			b[bytesCopied++] = 0;
		}
		if (crced)
		{
			b[0] |= 0x40;
			b[bytesCopied++] = (byte) crc.length;
			System.arraycopy(crc, 0, b, bytesCopied, crc.length);
			bytesCopied += crc.length;
		}
		if ((maxTagSize != -1) || textEncode || (maxTextSize != -1) || imageEncode || (imageRestrict != -1))
		{
			b[0] |= 0x20;
			b[bytesCopied++] = 0x01;
			byte restrict = 0;
			if (maxTagSize != -1) restrict |= (byte)((maxTagSize&0x3)<<6);
			if (textEncode) restrict |= 0x20;
			if (maxTextSize != -1) restrict |= (byte)((maxTextSize&0x3)<<3);
			if (imageEncode) restrict |= 0x04;
			if (imageRestrict != -1) restrict |= (byte)(imageRestrict&0x3);
			b[bytesCopied++] = restrict;
		}

		return b;
	}
912621
function parseImageOption(){ // (type,quality,option)のはず
	var imageopt = {};
	var type = pzpr.Candle.current;
	var cellsize = null, bgcolor = null, quality = null;
	for(var i=0;i<arguments.length;i++){
		var argv = arguments[i];
		switch(typeof argv){
			case 'string':
				type = argv;
				break;
			case 'number':
				if(argv>1.01){ cellsize = argv;}else{ quality = argv;}
				break;
			case 'object':
				if('cellsize' in argv){ cellsize = argv.cellsize;}
				if('bgcolor'  in argv){ bgcolor  = argv.bgcolor;}
				break;
		}
	}
	
	imageopt.type = ((type||pzpr.Candle.current).match(/svg/)?'svg':'canvas');
	imageopt.mimetype = (imageopt.type!=='svg' ? 'image/'+type : 'image/svg+xml');
	if(quality!==null && quality!==void 0){ imageopt.quality = quality;}
	
	if(cellsize!==null){ imageopt.cellsize = cellsize;}
	if(bgcolor !==null){ imageopt.bgcolor  = bgcolor;}
	
	return imageopt;
}