4

如何更改和访问存储在图像特定位置的颜色值?

我试图用坐标 (10, 10) 处的像素更改保存图像。我将红色值更改为值 65 以表示 ASCII 字符A。但是当我尝试从位置 (10, 10) 中提取值时,像素的红色值不等于预期值。

这是我更改图像的代码:

int pixelColor = bitmapImage.getPixel(10, 10);

int pixelAlpha = Color.alpha(pixelColor);
int red = 65; // represents character A
int green = Color.green(pixelColor);
int blue = Color.blue(pixelColor);

int new_pixel = Color.argb(pixelAlpha, red, green, blue);

bitmapImage.setPixel(10, 10, new_pixel);   

这是我提取值的代码:

String data = "";
int pixelColor = bitmapImage.getPixel(10, 10);
int red = Color.red(pixelColor); 
data += (char)red;

Toast.makeText(this, "Data: " + data, 20).show();

那么如何提取指定值呢?我想用 ASCII 字符替换红色值。我是否正确实施(LSB)算法?

这是我的完整程序:

public void saveImage(Bitmap bitmapImage, String name) throws IOException
{
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    String fName = "/mnt/sdcard/pictures/" + name + ".jpg";
    File f = new File(fName);
    f.createNewFile();

    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    fo.flush();
    fo.close();
}

private Bitmap HideMessage(Bitmap src)
{
    Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());

    for(int x = 0; x < src.getWidth(); x++)
    {
        for(int y = 0; y < src.getHeight(); y++)
        {
            dest.setPixel(x, y, src.getPixel(x, y));
        }
    }

    int pixelColor = src.getPixel(10, 10);

    int pixelAlpha = Color.alpha(pixelColor);
    int red = 65; // represent character A
    int green = Color.green(pixelColor);
    int blue = Color.blue(pixelColor);

    int new_pixel = Color.argb(pixelAlpha, red, green, blue);

    dest.setPixel(10, 10, new_pixel);            

    return dest;
}

public void Hide()
{    
    Bitmap dest = HideMessage(image);

    try 
    {
        saveImage(dest, "hidden");
        Toast.makeText(this, "Message Hidden in Image and saved", Toast.LENGTH_LONG).show();
    } 
    catch (IOException e) 
    {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
}

public void Show_character()
{
    Bitmap dest = BitmapFactory.decodeFile("/mnt/sdcard/pictures/hidden.jpg");

    String data = "";
    int pixelColor = dest.getPixel(10,10);
    int red = Color.red(pixelColor); 
    data += (char)red;

    Toast.makeText(this, "Data: " + data, 20).show();  
}
4

0 回答 0