Paintable Canvas Generated Image Quality Poor

Hello,
I have a RESTful API that returns a pixel array from MATLAB. I convert this into a java image and pass it to a paintable canvas. However, the paintable canvas output looks pixelated compared to the original image. How can I improve the image?

The API code looks like this (After the API returns the IMG pixel array of size IMGSize):

Img=[[[0, 0, 0] for i in range(IMGSize[1])] for j in range(IMGSize[0])]

n=-1
for k in range(IMGSize[2]):
	for j in range(IMGSize[1]):
		for i in range(IMGSize[0]):
			n+=1
			Img[i][j][k]=IMG[n]


image = BufferedImage(560, 420, BufferedImage.TYPE_INT_RGB);
raster = image.getData();
sm = raster.getSampleModel();
writeRaster = Raster.createWritableRaster(sm,Point(0,0))
for i in range(560):
	for j in range(420):
		for k in range(3):
			writeRaster.setSample(i, j, k, Img[j][i][k])
image.setData(writeRaster);

imageBytes=ByteArrayOutputStream()
ImageIO.write(image, "jpg", imageBytes)
imageBytes=imageBytes.toByteArray()
event.source.parent.getComponent('Figure').putClientProperty('Picture',imageBytes)

The paintable canvas code looks like this:

from java.io import ByteArrayInputStream
from javax.imageio import ImageIO
bytes = event.source.getClientProperty("Picture")
if bytes:
	image = ImageIO.read(ByteArrayInputStream(bytes))
	canvasW = event.width
	canvasH = event.height
	imageW = image.getWidth()
	imageH =  image.getHeight()
	print(imageW,imageH)
	scaleX = (canvasW-1.0) / imageW
	scaleY = (canvasH-1.0) / imageH
#	event.graphics.drawImage(image,0,0,event.source)
	g = event.graphics
	g.scale(scaleX, scaleY)
	g.drawImage(image,0,0,event.source)

The original image looks like this:
image
The paintable canvas image looks like this:

1 Like

Try not using JPEG. It is lossy, and the default quality is pretty low, IIRC. Or even better, just put the BufferedImage itself into the JComponent client property (instead of the bytes). Should run faster, too.

2 Likes

I tried bmp and png. I also passed the buffered image instead of bytes. But I did not see a noticeable difference, though this is good to know for future applications. I wonder if MATLAB is doing something behind the scenes to improve their image quality.

I bet they're rendering it with anti-aliasing, but whatever method you're using to get the raw pixels is not getting the final image. I think you're faithfully reproducing the pixels you've gotten from the API.

3 Likes

I tried this but saw no improvement.

import java.awt.RenderingHints as RenderingHints
...
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON)

Wouldn't expect any, you're just filling a raster image with pixel data, not using the drawing APIs.