80 lines
2.1 KiB
C++
80 lines
2.1 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
#include <stdexcept>
|
|
#include <cstdlib>
|
|
|
|
#define STB_IMAGE_IMPLEMENTATION
|
|
#include "stb_image.h"
|
|
|
|
struct RGB {
|
|
unsigned char r;
|
|
unsigned char g;
|
|
unsigned char b;
|
|
};
|
|
|
|
RGB getPixelColor(const std::string& filename, int x, int y) {
|
|
int width, height, channels;
|
|
|
|
// Load image into memory
|
|
unsigned char* data = stbi_load(filename.c_str(), &width, &height, &channels, 0);
|
|
if (!data) {
|
|
throw std::runtime_error("Failed to load image: " + filename);
|
|
}
|
|
|
|
// Validate coordinates
|
|
if (x < 0 || y < 0 || x >= width || y >= height) {
|
|
stbi_image_free(data);
|
|
throw std::out_of_range("Pixel coordinates out of range.");
|
|
}
|
|
|
|
// Calculate pixel index
|
|
int index = (y * width + x) * channels;
|
|
|
|
RGB color = { 0, 0, 0 };
|
|
if (channels >= 3) { // RGB or RGBA
|
|
color.r = data[index + 0];
|
|
color.g = data[index + 1];
|
|
color.b = data[index + 2];
|
|
}
|
|
else if (channels == 1) {
|
|
color.r = color.g = color.b = data[index];
|
|
}
|
|
|
|
// Free image memory
|
|
stbi_image_free(data);
|
|
return color;
|
|
}
|
|
|
|
int main() {
|
|
try {
|
|
std::string filename;
|
|
int x, y;
|
|
|
|
std::cout << "Enter image file path: ";
|
|
std::getline(std::cin, filename);
|
|
|
|
// Strip surrounding quotes if present
|
|
if (filename.size() >= 2 && filename.front() == '"' && filename.back() == '"') {
|
|
filename = filename.substr(1, filename.size() - 2);
|
|
}
|
|
|
|
std::cout << "Lade Bild von: " << filename << "\n";
|
|
|
|
std::cout << "Enter pixel coordinates (x y): ";
|
|
if (!(std::cin >> x >> y)) {
|
|
throw std::invalid_argument("Invalid coordinates input.");
|
|
}
|
|
|
|
RGB color = getPixelColor(filename, x, y);
|
|
std::cout << "Pixel at (" << x << ", " << y << ") -> "
|
|
<< "R: " << static_cast<int>(color.r) << ", "
|
|
<< "G: " << static_cast<int>(color.g) << ", "
|
|
<< "B: " << static_cast<int>(color.b) << "\n";
|
|
}
|
|
catch (const std::exception& e) {
|
|
std::cerr << "Error: " << e.what() << "\n";
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
} |