2012-04-19 633 views
0

我正在Android上创建一个应用程序,我需要操纵我的JPG文件。我没有获得JPG格式的标题信息,因此我将它转换为位图,处理位图中的像素值,然后再将其转换回JPG。在Android的JPG图像编码和解码

这里我面对的是什么问题 - 操作位图后只有一些像素和 转换回JPG,我没有得到我以前得到的相同的像素集(对于那些我没有操作的像素)。我在新图像中获得与原始图像相同的图像。但是,当我检查新的图像的像素值进行解码,未被破坏的像素是不同的...

File imagefile = new File(filepath); 
FileInputStream fis = new FileInputStream(imagefile); 
Bitmap bi = BitmapFactory.decodeStream(fis); 
int intArray[]; 
bi=bi.copy(Bitmap.Config.ARGB_8888,true);  
intArray = new int[bi.getWidth()*bi.getHeight()]; 
bi.getPixels(intArray, 0, bi.getWidth(), 0, 0, bi.getWidth(), bi.getHeight()); 

int newArray[] = encodeImage(msgbytes,intArray,mbytes); // method where i am manipulating my pixel values 

// converting the bitmap data back to JPG file 
bi = Bitmap.createBitmap(newArray, bi.getWidth(), bi.getHeight(), Bitmap.Config.ARGB_8888); 

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] data = baos.toByteArray(); 

Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length); 
String filepath = "/sdcard/image/new2.jpg"; 
File imagefile = new File(filepath); 
FileOutputStream fos = new FileOutputStream(imagefile); 
bitmapimage.compress(CompressFormat.JPEG, 100, fos); 

帮助我,如果我错了地方,还是我应该用一些其他的方法来操纵JPG像素值...

回答

3

JPEG是通常基于lossy compression的图像格式。这意味着一些对人眼不重要的信息会被丢弃以进一步缩小文件大小。尝试将图像保存为PNG(无损格式)。

+0

是的,但我需要将它保存为JPG文件,因为大多数移动用户使用JPG图像文件....有没有办法,我可以做所有我的编码在JPG n仍然能够检索所有数据? – Tani 2012-04-19 19:00:40

+0

取决于您使用_retrieve查看所有data_的含义。默认情况下,JPEG是一种有损格式,只需少量操作(例如裁剪和旋转)即可完成,而不会损失JPEG的更多信息。至少如果您使用SDK提供的方法打开并保存图像,您将失去信息。 – Niels 2012-04-19 19:25:33

0

小心使用

Bitmap bi = BitmapFactory.decodeStream(fis); 
bi = bi.copy(Bitmap.Config.ARGB_8888, true); 

在点,你必须第一bi你可能已经失去了很多的信息,而不是尝试使用BitmapFactory.Options强制8888(这是默认的太):

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inPreferredConfig = Bitmap.Config.ARGB_8888; 
options.inDither = false; 
Bitmap bi = BitmapFactory.decodeStream(fis, options); 

如果你留在copy你应该仍然recycle()扔掉。