There is no built-in function to convert Java images into MATLAB images. However using the Java API you can extract the data from a Java image and store it as a matrix, which is MATLAB's image representation.
Below is an example of converting a MATLAB image to Java and back to a MATLAB image. The image used in this example is part of the MATLAB demos and is on the MATLAB path. In this example, the "getPixels" function of the Java class "Raster" returns the RGB values for the image.
Depending upon the format of your Java image, additional work may be required. Java images can be stored in one of many formats; the "getPixels" function returns the pixel data in that format. For more information, see the javadoc page for the java.awt.image.Raster class at
<http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/Raster.html>
I = imread('office_3.jpg');
javaImage = im2java(I);
H=javaImage.getHeight;
W=javaImage.getWidth;
B = uint8(zeros([H,W,3]));
pixelsData = uint8(javaImage.getBufferedImage.getData.getPixels(0,0,W,H,[]));
for i = 1 : H
base = (i-1)*W*3+1;
B(i,1:W,:) = deal(reshape(pixelsData(base:(base+3*W-1)),3,W)');
end
imshow(B);
The following are two other ways to implement this (in a more optimized manner):
Example 1: (Faster execution)
pixelsData = reshape(typecast(jImage.getData.getDataStorage, 'uint8'), 4, w, h);
imgData = cat(3, ...
transpose(reshape(pixelsData(3, :, :), w, h)), ...
transpose(reshape(pixelsData(2, :, :), w, h)), ...
transpose(reshape(pixelsData(1, :, :), w, h)));
Example 2:
imgData = zeros([H,W,3],'uint8');
pixelsData = reshape(typecast(javaImage.getBufferedImage.getData.getDataStorage,'uint32'),W,H).';
imgData(:,:,3) = bitshift(bitand(pixelsData,256^1-1),-8*0);
imgData(:,:,2) = bitshift(bitand(pixelsData,256^2-1),-8*1);
imgData(:,:,1) = bitshift(bitand(pixelsData,256^3-1),-8*2);
Best Answer