Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
8 / 8 / 4
Регистрация: 08.12.2022
Сообщений: 157

Выход за границы в методе изменения размера изображения

27.09.2024, 19:53. Показов 1615. Ответов 20
Метки c++ (Все метки)

Студворк — интернет-сервис помощи студентам
Мне необходимо реализовать метод изменения размера изображения. Написал его, но постоянно получаю выход за границы. Подскажите где не так написал. В предоставленном коде в функции main условное использование этого метода(в основной программе использоваться будет так же)

image.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#pragma once
 
#include <array>
#include <cassert>
#include <cstddef>
#include <vector>
#include <string>
#include <stdexcept>
#include <filesystem>
#include <fstream>
 
namespace img_lib
{
    using namespace std::string_literals;
    using Path = std::filesystem::path;
 
    struct Color
    {
        Color() = default;
        Color(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}
        Color(uint8_t r_, uint8_t g_, uint8_t b_, uint8_t a_) : r(r_), g(g_), b(b_), a(a_) {}
 
        static Color Black()
        {
            return { 0, 0, 0, 255 };
        }
 
        static Color White()
        {
            return { 255, 255, 255, 255 };
        }
 
        uint8_t r;
        uint8_t g;
        uint8_t b;
        uint8_t a;
 
        Color operator*(float scalar_) const
        {
            return
            {
                static_cast<uint8_t>(r * scalar_),
                static_cast<uint8_t>(g * scalar_),
                static_cast<uint8_t>(b * scalar_),
                static_cast<uint8_t>(a * scalar_)
            };
        }
 
        Color operator+(const Color& other_) const
        {
            return
            {
                static_cast<uint8_t>(r + other_.r),
                static_cast<uint8_t>(g + other_.g),
                static_cast<uint8_t>(b + other_.b),
                static_cast<uint8_t>(a + other_.a)
            };
        }
 
        Color& operator+=(const Color& other_)
        {
            r += other_.r;
            g += other_.g;
            b += other_.b;
            a += other_.a;
            return *this;
        }
    };
 
    class Image
    {
    public:
 
        Image() = default;
        Image(int w_, int h_) : width(w_), height(h_) {}
        Image(int w_, int h_, Color fill_);
 
        Image(const Image& other_);
        Image& operator=(const Image& other_);
 
        Image(Image&& other_) noexcept;
        Image& operator=(Image&& other_) noexcept;
 
        explicit operator bool() const
        {
            return GetWidth() > 0 && GetHeight() > 0;
        }
 
        bool operator!() const
        {
            return !operator bool();
        }
 
        const Color& GetPixel(int x_, int y_) const;
        Color& GetPixel(int x_, int y_);
 
        std::vector<Color>& GetPixels();
        const std::vector<Color>& GetPixels() const;
 
        Color* GetLine(int y_);
        const Color* GetLine(int y_) const;
 
        int GetWidth() const;
        int GetHeight() const;
 
        int GetStep() const;
 
        const uint8_t* GetData() const;
 
        void SetPixel(int x, int y, const Color& pixel);
 
        Image ResizeImage(int newWidth_, int newHeight_) const;
 
    private:
 
        int width = 0;
        int height = 0;
        int step = 0;
 
        std::vector<Color> pixels;
 
        void CheckBounds(int x_, int y_) const;
        Color BilinearInterpolation(const Color& c00_, const Color& c01_, const Color& c10_, const Color& c11_, float dx_, float dy_) const;
    };
 
}//end namespace img_lib
image.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#include "image.h"
 
namespace img_lib
{
    Image::Image(int w_, int h_, Color fill_) : width(w_), height(h_), step(w_), pixels(w_* h_, fill_) {}
 
    Image::Image(const Image& other_) : width(other_.width), height(other_.height), step(other_.step), pixels(other_.pixels) {}
 
    Image::Image(Image&& other_) noexcept : width(other_.width), height(other_.height), step(other_.step), pixels(std::move(other_.pixels))
    {
        other_.width = 0;
        other_.height = 0;
        other_.step = 0;
    }
 
    Image& Image::operator=(const Image& other_)
    {
        if (this != &other_)
        {
            width = other_.width;
            height = other_.height;
            step = other_.step;
            pixels = other_.pixels;
        }
        return *this;
    }
 
    Image& Image::operator=(Image&& other_) noexcept
    {
        if (this != &other_)
        {
            width = other_.width;
            height = other_.height;
            step = other_.step;
            pixels = std::move(other_.pixels);
 
            other_.width = 0;
            other_.height = 0;
            other_.step = 0;
        }
        return *this;
    }
 
    const Color& Image::GetPixel(int x_, int y_) const
    {
        CheckBounds(x_, y_);
        return pixels[y_ * step + x_];
    }
 
    Color& Image::GetPixel(int x_, int y_)
    {
        CheckBounds(x_, y_);
        return pixels[y_ * step + x_];
    }
 
    void Image::SetPixel(int x_, int y_, const Color& pixel_)
    {
        pixels[y_ * width + x_] = pixel_;
    }
 
    std::vector<Color>& Image::GetPixels()
    {
        return pixels;
    }
 
    const std::vector<Color>& Image::GetPixels() const
    {
        return pixels;
    }
 
    Color* Image::GetLine(int y_)
    {
        CheckBounds(0, y_);
        return &pixels[y_ * step];
    }
 
    const Color* Image::GetLine(int y_) const
    {
        CheckBounds(0, y_);
        return &pixels[y_ * step];
    }
 
    int Image::GetWidth() const
    {
        return width;
    }
 
    int Image::GetHeight() const
    {
        return height;
    }
 
    int Image::GetStep() const
    {
        return step;
    }
 
    const uint8_t* Image::GetData() const
    {
        if (pixels.empty())
        {
            return nullptr;
        }
        return reinterpret_cast<const uint8_t*>(pixels.data());
    }
 
    Image Image::ResizeImage(int newWidth_, int newHeight_) const
    {
        Image newImage(newWidth_, newHeight_);
 
        float scaleX = static_cast<float>(width) / newWidth_;
        float scaleY = static_cast<float>(height) / newHeight_;
 
        for (int y = 0; y < newHeight_; ++y)
        {
            for (int x = 0; x < newWidth_; ++x)
            {
                float srcX = (x + 0.5f) * scaleX - 0.5f;
                float srcY = (y + 0.5f) * scaleY - 0.5f;
 
                int x0 = static_cast<int>(srcX);
                int y0 = static_cast<int>(srcY);
                int x1 = x0 + 1;
                int y1 = y0 + 1;
 
                float dx = srcX - x0;
                float dy = srcY - y0;
 
                Color c00 = GetPixel(x0, y0);
                Color c01 = GetPixel(x0, y1);
                Color c10 = GetPixel(x1, y0);
                Color c11 = GetPixel(x1, y1);
 
                Color interpolatedColor = BilinearInterpolation(c00, c01, c10, c11, dx, dy);
                newImage.SetPixel(x, y, interpolatedColor);
            }
        }
 
        return newImage;
    }
 
    Color Image::BilinearInterpolation(const Color& c00_, const Color& c01_, const Color& c10_, const Color& c11_, float dx_, float dy_) const
    {
        Color result;
 
        result.r = static_cast<uint8_t>
            (
                (1 - dx_) * (1 - dy_) * c00_.r +
                (1 - dx_) * dy_ * c01_.r +
                dx_ * (1 - dy_) * c10_.r +
                dx_ * dy_ * c11_.r
            );
 
        result.g = static_cast<uint8_t>
            (
                (1 - dx_) * (1 - dy_) * c00_.g +
                (1 - dx_) * dy_ * c01_.g +
                dx_ * (1 - dy_) * c10_.g +
                dx_ * dy_ * c11_.g
            );
 
        result.b = static_cast<uint8_t>
            (
                (1 - dx_) * (1 - dy_) * c00_.b +
                (1 - dx_) * dy_ * c01_.b +
                dx_ * (1 - dy_) * c10_.b +
                dx_ * dy_ * c11_.b
            );
 
        result.a = static_cast<uint8_t>
            (
                (1 - dx_) * (1 - dy_) * c00_.a +
                (1 - dx_) * dy_ * c01_.a +
                dx_ * (1 - dy_) * c10_.a +
                dx_ * dy_ * c11_.a
            );
 
        return result;
    }
 
    void Image::CheckBounds(int x_, int y_) const
    {
        if (x_ < 0 || x_ >= width || y_ < 0 || y_ >= height)
        {
            throw std::out_of_range("Pixel coordinates out of range"s);
        }
    }
 
}//end namespace img_lib
main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "image.h"
 
using namespace std;
using namespace img_lib;
 
int main()
{
    Image image(100, 100);
 
    cout << image.GetHeight() << " - " << image.GetWidth() << endl;
 
    image.ResizeImage(200, 200);
 
    cout << image.GetHeight() << " - " << image.GetWidth() << endl;
}
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.09.2024, 19:53
Ответы с готовыми решениями:

Выход за границы диапазона изменения индекса
var df1,df2,df3:array of char; i,j,zx:byte; begin for i:=1 to 5 do read (df1,df2); for i:=1 to 50 do for j:=1 to 50 do if...

Выход за границы диапазона изменения индекса
Задача кластерного анализа. Как исправить ошибку: выход за границы диапазона изменения индекса 1..1 (строка 101)? И можно ли сделать,...

выход за границы диапазона изменения индекса
var A : array of integer ; xa1:integer; begin randomize; a:=random(800); a:=1+random(900); xa1:=a+a; ...

20
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
13177 / 6813 / 1821
Регистрация: 18.10.2014
Сообщений: 17,237
29.09.2024, 09:21
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от Ifreqo Посмотреть сообщение
Вылетало действительно каждый раз на GetPixel
Еще раз повторяю: если "вылетало действительно каждый раз на GetPixel", то вылетает и сейчас. Данное исправление никакого отношения к GetPixel не имеет.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
29.09.2024, 09:21
Помогаю со студенческими работами здесь

Выход за границы диапазона изменения индекса
выход за границы диапазона изменения индекса,строка 53 Program 6; uses crt; const z=20; type mas=array of real; var a:mas; ...

Выход за границы диапазона изменения индекса
Доброго времени суток! При компиляции ошибка: »*Ошибка: 100001 - выход за границы диапазона изменения индекса 0..100000...

Выход за границы диапазона изменения индекса.
Помогите пожалуйста разобраться с ошибкой, выдаётся в 43 строке, причём не всегда. А задача такова: рандомом задать массив из 10 чисел от...

Выход за границы диапазона изменения индекса
const n=12; type mas=array of integer; var a,b:mas;i,j,jmin,jmax,j1,j2,k: integer; procedure vvod (var a:mas); var...

Ошибка: выход за границы диапозона изменения индекса
Помогите исправить ошибку в коде ниже: const L=10; W=30; var txt:array of char; x:char; i, j: integer; begin ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
21
Ответ Создать тему
Новые блоги и статьи
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
Модульная разработка через nuget packages
DevAlt 07.03.2026
Сложившийся в . Net-среде способ разработки чаще всего предполагает монорепозиторий в котором находятся все исходники. При создании нового решения, мы просто добавляем нужные проекты и имеем. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru