使用ifstream读取和编辑jpg文件的C++代码

3

我正在尝试开展一个简单的图像加密项目,有几个问题想要问。

  1. Should I store each byte of data from ifstream into a character like I did in my code?

  2. Each byte printed is a weird symbol (which is correct), but why does adding 10(an int) to that always results in a number when printed?

    int main() {
    
        vector <char> data; // Stores each byte from image.jpg
    
        ifstream fileIn("image.jpg", ios::binary);
    
        int i = 0; // Used for accessing each item in data vector
    
        while (fileIn){
    
                //Add each character from the image file into the vector
                data.push_back(fileIn.get());
    
                cout <<  "Original: " << data[i] << endl; // Print each character from image.jgp
    
                cout << "Result after adding: " << data[i] + 10 << endl; // This line is where I need help with
    
                i++;
    
                system("pause");
        }
    
        fileIn.close();
    
        system("pause");
        return 0;
    }
    

输出:

Original:  å
Result after adding: -112

Original:  Æ
Result after adding: -100

Original:
Result after adding: 12

正如您所看到的,增加10总是会得到一个数字。我该如何正确地递增这些值,以便稍后可以将其更改回来?

感谢任何帮助。


只是为了澄清一下,您并不会对实际的JPEG图像数据进行任何操作吗?只是您的输入文件恰好是一个JPEG图像文件? - Some programmer dude
1个回答

3
当你使用比 int 类型小的类型(例如在你的情况下是 char)进行算术运算(如加法)时,该值将被提升为 int 并使用两个 int 值进行操作。
因此,表达式 data[i] + 10 等同于 static_cast<int>(data[i]) + 10
了解更多关于integral promotionarithmetic operator conversions的信息。
关于如何解决你的问题,首先你必须确保操作的结果实际上适合一个 char。如果你读取的字节是 127 并且加上 10,那么结果就超出了 signed char 的范围(似乎这就是你所拥有的)。
如果结果没有超出范围,那么你可以直接进行强制类型转换:
char result = static_cast<char>(data[i] + 10);

作为一个小的侧记,如果你正在读取二进制数据,那么你实际上并没有读取“字符”,因此我建议使用固定宽度整数类型,例如int8_tuint8_t,而不是char。在支持的平台上(现在几乎所有平台都支持),它们只是signed charunsigned char的别名(分别),但使用别名对于你代码的读者更具信息性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接