Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/3: Рейтинг темы: голосов - 3, средняя оценка - 5.00
1 / 1 / 4
Регистрация: 24.10.2014
Сообщений: 200
1

Преобразование изображений в bmp формате

24.03.2020, 02:34. Показов 624. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Написание программы для картинок формата bmp с условием "Растягивание в ширину в M раз".

Я тут начал писать код, но не совсем пойму как реализовать эту функцию...

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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <string>
#include <iostream>
#include <fstream>
#include <math.h>
 
 
using namespace std;
 
 
#pragma pack(push, 1)
 
typedef struct tBITMAPFILEHEADER
{
    WORD bfType;
    DWORD bfSize;
    WORD bfReserved1;
    WORD bfReserved2;
    DWORD bfOffBits;
}sFileHead;
 
typedef struct tBITMAPINFOHEADER
{
    DWORD biSize;
    LONG biWidth;
    LONG biHeight;
    WORD biPlanes;
    WORD biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG biXPelsPerMeter;
    LONG biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
}sInfoHead;
 #pragma (pop)
 
sFileHead FileHead;
sInfoHead InfoHead;
 
struct Color
{
    BYTE red;
    BYTE green;
    BYTE blue;
};
 
int pixel_size = sizeof(Color);
 
 
//1 - BMP, 2 - CMP
int img_type = 0;
 
 
Color *src_image = 0;
 
Color *dst_image = 0;
 
 
int width = 0;
int height = 0;
 
 
void ShowBMPHeaders(tBITMAPFILEHEADER fh, tBITMAPINFOHEADER ih)
{
    cout << "Type: " << (CHAR)fh.bfType << endl;
    cout << "Size: " << fh.bfSize << endl;
    cout << "Shift of bits: " << fh.bfOffBits << endl;
    cout << "Width: " << ih.biWidth << endl;
    cout << "Height: " << ih.biHeight << endl;
    cout << "Planes: " << ih.biPlanes << endl;
    cout << "BitCount: " << ih.biBitCount << endl;
    cout << "Compression: " << ih.biCompression << endl;
}
 
 
bool OpenImage(string path)
{
    ifstream img_file;
    Color temp;
    char buf[3];
 
    
    img_file.open(path.c_str(), ios::in | ios::binary);
    if (!img_file)
    {
        cout << "File isn`t open!" << endl;
        return false;
    }
 
 
    img_file.read((char*)&FileHead, sizeof(FileHead));
    img_file.read((char*)&InfoHead, sizeof(InfoHead));
 
    img_type = 1;
    ShowBMPHeaders(FileHead, InfoHead);
    
    width = InfoHead.biWidth;
    height = InfoHead.biHeight;
 
 
 
    src_image = new Color[width*height];
 
    int i, j;
    for (i = 0; i < height; i++)
    {
        for (j = 0; j < width; j++)
        {
            img_file.read((char*)&temp, pixel_size);
            src_image[i*width + j] = temp;
        }
        
        img_file.read((char*)buf, j % 4);
    }
    img_file.close();
 
    return true;
}
 
 
bool SaveImage(string path)
{
    ofstream img_file;
    char buf[3];
 
 
    img_file.open(path.c_str(), ios::out | ios::binary);
    if (!img_file)
    {
        return false;
    }
 
    img_file.write((char*)&FileHead, sizeof(FileHead));
    img_file.write((char*)&InfoHead, sizeof(InfoHead));
 
 
    if (dst_image == 0)
    {
        dst_image = new Color[width*height];
        memcpy(dst_image, src_image, width*height * sizeof(Color));
    }
 
 
    int i, j;
    for (i = 0; i < height; i++)
    {
        for (j = 0; j < width; j++)
        {
            img_file.write((char*)&dst_image[i*width + j], pixel_size);
        }
        img_file.write((char*)buf, j % 4);
    }
    img_file.close();
 
    return true;
}
 
 
void CopyDstToSrc()
{
    if (dst_image != 0)
    {
        memcpy(src_image, dst_image, width*height * sizeof(Color));
    }
}
 
 
void AddNoise(double probability)
{
    int size = width*height;
    int count = (int)(size*probability) / 100;
    int x, y;
    long pos;
    for (int i = 0; i < count; i++)
    {
        x = rand() % width;
        y = rand() % height;
        pos = y*width + x;
        src_image[pos].blue =rand () %255;
        src_image[pos].green =rand () %255;
        src_image[pos].red =rand () %255;
    }
    cout << "Point was added: " << count << endl;
}
 
 
void ShowImage(string path)
{
    ShowBMPHeaders(FileHead, InfoHead);
    system(path.c_str());
}
 
 
void ReadPath(string &str)
{
    str.clear();
    cout << "Enter path to image" << endl;
    cin >> str;
}
 
 
BYTE brightness(Color color)
{
    return (BYTE)0.3*color.red + 0.59*color.green + 0.11*color.blue;
}
 
 
void WidthOn()
{
    
 
}
 
 
int main(int argc, char* argv[])
{
    int m = 3;
    srand((unsigned)time(NULL));
    setlocale(LC_CTYPE, "");
 
    
    string path_to_image, temp, filter;
 
    
    cout << "             Лабораторная работа по ГиМС\n";
    cout << "   3. Растягивание в ширину в M раз\n";
    
     if (m == 3)
    {
        ReadPath(path_to_image);
        OpenImage(path_to_image);
        ShowImage(path_to_image);
        WidthOn();
        ReadPath(temp);
        SaveImage(temp);
        ShowImage(temp);
    }
 
 
    if (src_image != 0)
    {
        delete[] src_image;
    }
    
    if (dst_image != 0)
    {
        delete[] dst_image;
    }
    return 0;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
24.03.2020, 02:34
Ответы с готовыми решениями:

Сохранение изображений в формате png, gif, jpg, bmp
Сохраняя изображение из PictureBox в файл мы получаем несжатый битовый образ независимо от того...

Преобразование изображений в BMP
Доброго времени суток! Я знаю такой класс как Bitmap, но к сожалению он оказался очень медленным...

Создать таблицу 2х2 для отображения в ее ячейках изображений в формате *.bmp
Создать таблицу 2х2 для отображения в ее ячейках изображений в формате *.bmp.

Работа с разными типами изображений (преобразование к одному типу bmp)
Здравствуйте. Есть код: TImage *Infile = new TImage(); TMemoryStream *s = new TMemoryStream;...

3
1 / 1 / 4
Регистрация: 24.10.2014
Сообщений: 200
24.03.2020, 15:15  [ТС] 2
Здравствуйте. Не понимаю как растягивать, смог только написать на сжатие функцию, запутался в сторках.

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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <string>
#include <iostream>
#include <fstream>
#include <math.h>
 
 
using namespace std;
 
 
#pragma pack(push, 1)
 
typedef struct tBITMAPFILEHEADER
{
    WORD bfType;
    DWORD bfSize;
    WORD bfReserved1;
    WORD bfReserved2;
    DWORD bfOffBits;
}sFileHead;
 
typedef struct tBITMAPINFOHEADER
{
    DWORD biSize;
    LONG biWidth;
    LONG biHeight;
    WORD biPlanes;
    WORD biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG biXPelsPerMeter;
    LONG biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
}sInfoHead;
 #pragma (pop)
 
sFileHead FileHead;
sInfoHead InfoHead;
 
struct Color
{
    BYTE red;
    BYTE green;
    BYTE blue;
};
 
int pixel_size = sizeof(Color);
 
 
//1 - BMP, 2 - CMP
int img_type = 0;
 
 
Color *src_image = 0;
 
Color *dst_image = 0;
 
 
int width = 0;
int height = 0;
 
 
void ShowBMPHeaders(tBITMAPFILEHEADER fh, tBITMAPINFOHEADER ih)
{
    cout << "Type: " << (CHAR)fh.bfType << endl;
    cout << "Size: " << fh.bfSize << endl;
    cout << "Shift of bits: " << fh.bfOffBits << endl;
    cout << "Width: " << ih.biWidth << endl;
    cout << "Height: " << ih.biHeight << endl;
    cout << "Planes: " << ih.biPlanes << endl;
    cout << "BitCount: " << ih.biBitCount << endl;
    cout << "Compression: " << ih.biCompression << endl;
}
 
 
bool OpenImage(string path)
{
    ifstream img_file;
    Color temp;
    char buf[3];
 
    
    img_file.open(path.c_str(), ios::in | ios::binary);
    if (!img_file)
    {
        cout << "File isn`t open!" << endl;
        return false;
    }
 
 
    img_file.read((char*)&FileHead, sizeof(FileHead));
    img_file.read((char*)&InfoHead, sizeof(InfoHead));
 
    img_type = 1;
    ShowBMPHeaders(FileHead, InfoHead);
    
    width = InfoHead.biWidth;
    height = InfoHead.biHeight;
 
 
 
    src_image = new Color[width*height];
 
    int i, j;
    for (i = 0; i < height; i++)
    {
        for (j = 0; j < width; j++)
        {
            img_file.read((char*)&temp, pixel_size);
            src_image[i*width + j] = temp;
        }
        
        img_file.read((char*)buf, j % 4);
    }
    img_file.close();
 
    return true;
}
 
 
bool SaveImage(string path)
{
    ofstream img_file;
    char buf[3];
 
 
    img_file.open(path.c_str(), ios::out | ios::binary);
    if (!img_file)
    {
        return false;
    }
 
    img_file.write((char*)&FileHead, sizeof(FileHead));
    img_file.write((char*)&InfoHead, sizeof(InfoHead));
 
 
    if (dst_image == 0)
    {
        dst_image = new Color[width*height];
        memcpy(dst_image, src_image, width*height * sizeof(Color));
    }
 
 
    int i, j;
    for (i = 0; i < height; i++)
    {
        for (j = 0; j < width; j++)
        {
            img_file.write((char*)&dst_image[i*width + j], pixel_size);
        }
        img_file.write((char*)buf, j % 4);
    }
    img_file.close();
 
    return true;
}
 
 
void CopyDstToSrc()
{
    if (dst_image != 0)
    {
        memcpy(src_image, dst_image, width*height * sizeof(Color));
    }
}
 
 
void AddNoise(double probability)
{
    int size = width*height;
    int count = (int)(size*probability) / 100;
    int x, y;
    long pos;
    for (int i = 0; i < count; i++)
    {
        x = rand() % width;
        y = rand() % height;
        pos = y*width + x;
        src_image[pos].blue =rand () %255;
        src_image[pos].green =rand () %255;
        src_image[pos].red =rand () %255;
    }
    cout << "Point was added: " << count << endl;
}
 
 
void ShowImage(string path)
{
    ShowBMPHeaders(FileHead, InfoHead);
    system(path.c_str());
}
 
 
void ReadPath(string &str)
{
    str.clear();
    cout << "Enter path to image" << endl;
    cin >> str;
}
 
 
BYTE brightness(Color color)
{
    return (BYTE)0.3*color.red + 0.59*color.green + 0.11*color.blue;
}
 
 
void WidthOn()
{
 int v;
 
cout << "Enter M=";
cin >> v;
std::cin.clear();
std::cin.ignore();
 
if(v<=0) 
return;
 
dst_image = new Color[width/v*height];
 
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width/v; j++)
{
 
dst_image[i*width/v + j] = src_image[i*width + j*v];
}
}
width = width/v;
 
InfoHead.biWidth = InfoHead.biWidth/v;
FileHead.bfSize = 3*width*height+sizeof(FileHead)+sizeof(InfoHead)+(width%4)*height;
InfoHead.biSizeImage = 3*width*height+(width%4)*height;   
}
 
 
int main(int argc, char* argv[])
{
    int m = 3;
    srand((unsigned)time(NULL));
    setlocale(LC_CTYPE, "");
 
    
    string path_to_image, temp, filter;
 
    
    cout << "             Лабораторная работа по ГиМС\n";
    cout << "   3. Растягивание в ширину в M раз\n";
    
     if (m == 3)
    {
        ReadPath(path_to_image);
        OpenImage(path_to_image);
        ShowImage(path_to_image);
        WidthOn();
        ReadPath(temp);
        SaveImage(temp);
        ShowImage(temp);
    }
 
 
    if (src_image != 0)
    {
        delete[] src_image;
    }
    
    if (dst_image != 0)
    {
        delete[] dst_image;
    }
    return 0;
}
Добавлено через 1 час 27 минут
Подскажите пожалуйста, я не понимаю....

Добавлено через 36 минут
При видоизменении кода, с широтой и высотой, у меня получалось растягивать картинку, но у меня была копия её же, помогите, просто растянуть изображение по ширине!
0
2511 / 845 / 319
Регистрация: 10.02.2018
Сообщений: 1,984
24.03.2020, 16:43 3
Цитата Сообщение от ITALIANO Посмотреть сообщение
Подскажите пожалуйста, я не понимаю....
Есть разные способы растягивания/интерполирования: по ближайшему пикселю, линейно, кубически и более сложные.
Вам какой-то конкретный алгоритм растягивания нужен?
0
6126 / 3475 / 1412
Регистрация: 07.02.2019
Сообщений: 8,827
24.03.2020, 17:21 4
Цитата Сообщение от ITALIANO Посмотреть сообщение
Подскажите пожалуйста, я не понимаю....
если просто линейно интерполировать по ширине, то например как то так:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    //...
    int new_width = lround(v * width);
    double factor = (double)(width - 1) / (new_width - 1);
 
    dst_image = new Color[new_width * height];
 
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < new_width; j++)
        {
            int src_j = max(0, min(width - 1, lround(j * factor)));
            dst_image[i * new_width + j] = src_image[i * width + src_j];
        }
    }
    //...
0
24.03.2020, 17:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
24.03.2020, 17:21
Помогаю со студенческими работами здесь

График в формате bmp
Доброго времени суток, уважаемые форумчане. Есть довольно интересная проблемка - а именно - нужно...

Сохранение файла в bmp формате
Кaк сделaть чтoбы пoсле рисoвaния метoдaми line() и circle() мoжнo былo этo сoхрaнить кaк .БМП...

Создание графиков в формате bmp
Как, используя средства C++ Builder, построить двумерный график с указанием масштаба на осях...

Обработка .bmp изображений
Помогите пожалуйста с програмкой до этого делал в маткаде) а сейчас надо в билдере по тихоньку...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru