473,396 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Replace an image in C using binary mode

109 100+
Hi I'm trying to open up a .jpg file in binary mode using C and replace it with another .jpg file. This is my code so far:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main() {
  5.  
  6.     FILE *background;
  7.     background=fopen( "c:\\Dave\\C-programming\\stbedes.jpg", "w+b" );
  8.     FILE *newpic;
  9.     newpic=fopen( "c:\\Dave\\C-programming\\newpic.jpg", "rb" );
  10.     fwrite(newpic, sizeof(newpic), sizeof(newpic)/sizeof(newpic), background);
  11.     fclose(background);
  12.     getchar();
  13. }
I know that if it was a text file then I would do this:

Expand|Select|Wrap|Line Numbers
  1.     FILE *background;
  2.     background=fopen( "c:\\Dave\\C-programming\\stbedes.jpg", "w+b" );
  3.     char x[12]="Hello World";
  4.     fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), );
  5.     fclose(background);
  6.  
I assumed that I simply needed to replace the line where I create the string with "Hello World" in it with a pointer to the picture I wanted to have in the new file. I then replaced all the instances of x in the fwrite function with newpic because it is the pointer to the picture I want to use.

It is probably a lot more complicated than this so any ideas as to why this hasn't worked and how I can transfer the picture in newpic.jpg to stbedes.jpg?
May 20 '07 #1
40 3069
DeMan
1,806 1GB
I think you need to read the contents you want to write first (that is read newpic into an array (characters should be ok ) before trying to write it ot background pic).
May 20 '07 #2
DeMan
1,806 1GB
scrub that....
The size you enter should be the size of the file (which I'm not sure whether sizeof will return correctly).
You can use fseek to SEEK_END to set a pointer to the end of the file, and then use ftell to work out the size.
May 20 '07 #3
niskin
109 100+
scrub that....
The size you enter should be the size of the file (which I'm not sure whether sizeof will return correctly).
You can use fseek to SEEK_END to set a pointer to the end of the file, and then use ftell to work out the size.
ok forgive me for perhaps sounding a bit newbie here, but in stdio.h it says the syntax is this:

fseek (FILE*, long, int);

and

ftell (FILE*);

I'm not entirely sure what to put in 'long' in fseek and whether either of these are supposed to display any information on the screen?
May 21 '07 #4
weaknessforcats
9,208 Expert Mod 8TB
Neither of these display information.

Use SEEK_END with fseek. That will position the file cursor to the end of the file. Next, call ftell() to return the byte displacement from the begining of the file. That will be the file size you need to read into memory using a single fread().
May 21 '07 #5
niskin
109 100+
Neither of these display information.

Use SEEK_END with fseek. That will position the file cursor to the end of the file. Next, call ftell() to return the byte displacement from the begining of the file. That will be the file size you need to read into memory using a single fread().
ok slowly getting there. So far I have:

#include "stdio.h"
#include "stdlib.h"

int main() {

int x;
FILE *newpic;
newpic=fopen("c:\\Dave\\C-programming\\newpic.jpg", "rb");
fseek (newpic, SEEK_END , x);
fread(x, ftell(x), ftell(x)/ftell(x), newpic);
FILE *background;
background=fopen("c:\\Dave\\C-programming\\stbedes.jpg", "wb");
fwrite(x, ftell(x), ftell(x)/ftell(x), background);
}

My compiler is coming up with errors for the lines with fread and fwrite.
What am I doing wrong?
May 21 '07 #6
weaknessforcats
9,208 Expert Mod 8TB
This compiles but I did not test it:
Expand|Select|Wrap|Line Numbers
  1. FILE *newpic;
  2. int* x;
  3. newpic=fopen("c:\\Dave\\C-programming\\newpic.jpg", "rb");
  4. //
  5. //WeaknessForCats
  6. //You need to seek from the origin (byte 0) of the file)
  7. //                                        V
  8. fseek (newpic, SEEK_END ,0);
  9. //
  10. //Now determine file size:
  11. //ftell() will return the position of the end of the file.
  12. //That's where fseek has positioned the cursor.
  13. int length = ftell(newpic);
  14. //
  15. //Now create an array of the correct size:
  16. //
  17. x = (int*)malloc(length * sizeof(int));
  18. fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), newpic);
  19. FILE *background;
  20. background=fopen("c:\\Dave\\C-programming\\stbedes.jpg", "wb");
  21. fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), background);
  22. //
  23. //Dont forget to delete the array
  24. //
  25. free(x);
  26.  
May 21 '07 #7
niskin
109 100+
Thanks but unfortunately it didn't work. I'm not entirely sure what malloc does and I presume int* is some kind of pointer.

I opened up stbedes.jpg in notepad to see if it actually had anything in it but it did not have more than a single symbol so perhaps the program only copied 1 character into the file? If so, would fputc be of any use?
May 21 '07 #8
Savage
1,764 Expert 1GB
Thanks but unfortunately it didn't work. I'm not entirely sure what malloc does and I presume int* is some kind of pointer.

I opened up stbedes.jpg in notepad to see if it actually had anything in it but it did not have more than a single symbol so perhaps the program only copied 1 character into the file? If so, would fputc be of any use?
malloc alocates memory so that fread can read in a specifed amount of data(specifed by secound fread argument) from the block which x points.

Savage
May 21 '07 #9
niskin
109 100+
This compiles but I did not test it:
Expand|Select|Wrap|Line Numbers
  1. FILE *newpic;
  2. int* x;
  3. newpic=fopen("c:\\Dave\\C-programming\\newpic.jpg", "rb");
  4. //
  5. //WeaknessForCats
  6. //You need to seek from the origin (byte 0) of the file)
  7. //                                        V
  8. fseek (newpic, SEEK_END ,0);
  9. //
  10. //Now determine file size:
  11. //ftell() will return the position of the end of the file.
  12. //That's where fseek has positioned the cursor.
  13. int length = ftell(newpic);
  14. //
  15. //Now create an array of the correct size:
  16. //
  17. x = (int*)malloc(length * sizeof(int));
  18. fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), newpic);
  19. FILE *background;
  20. background=fopen("c:\\Dave\\C-programming\\stbedes.jpg", "wb");
  21. fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), background);
  22. //
  23. //Dont forget to delete the array
  24. //
  25. free(x);
  26.  
anybody know why this doesn't work?
May 22 '07 #10
weaknessforcats
9,208 Expert Mod 8TB
I said I didn't test it. The bug is here:
Expand|Select|Wrap|Line Numbers
  1. fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), newpic);
  2.  
x is an int*. So sizeof(x) is the sizeof the pointer (4 bytes) divided by
sizeof(x[0]) which is the sizeof an int so now you have 4/4 or 1.

Use the length of the file.

This trick:

sizeof(x)/sizeof(x[0])

to get the number of elements in an array DOES NOT WORK in all cases. In fact, it works in only one case: The array is a stack variable in the function where you use this trick. In all other cases, the name of the array is the address of element 0 and an address is 4 bytes so you always get 4 for the sizeof the array.

C and C++ require that you keep the number of elements in a variable and you pass the variable around with the array name.

In fact, in C++, you shold be using a vector rather than an array. Issues like like are handled by the vector code. The number of elements in a vector is alwways vector<>::size().
May 22 '07 #11
niskin
109 100+
Ok thanks very much. I have put:

fread(x, sizeof(x[0]), length, newpic);

instead of:

fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), newpic);

Hasn't worked though lol. Did I do something wrong?
May 22 '07 #12
Savage
1,764 Expert 1GB
Ok thanks very much. I have put:

fread(x, sizeof(x[0]), length, newpic);

instead of:

fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), newpic);

Hasn't worked though lol. Did I do something wrong?
What do u mean it hasn't worked?

Is it still copying just one character or is it something else?

Savage
May 22 '07 #13
niskin
109 100+
What do u mean it hasn't worked?

Is it still copying just one character or is it something else?

Savage
Still seems to be copying one character when I open stbedes.jpg in notedpad. And when I try to view stbedes.jpg as a picture it has nothing to show. Not sure why that is. This is my source code:

#include "stdio.h"
#include "stdlib.h"

int main() {

FILE *newpic;
int* x;
newpic=fopen("c:\\Dave\\C-programming\\newpic.jpg", "rb");
fseek (newpic, SEEK_END ,0);.
int length = ftell(newpic);
x = (int*)malloc(length * sizeof(int));
fread(x, sizeof(x[0]), length, newpic);
FILE *background;
background=fopen("c:\\Dave\\C-programming\\stbedes.jpg", "wb");
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), background);
free(x);
}
May 22 '07 #14
DeMan
1,806 1GB
use length in your write as well as your read:
eg
Expand|Select|Wrap|Line Numbers
  1. fwrite(x, sizeof(x[0]), length, background);
  2.  
May 22 '07 #15
Savage
1,764 Expert 1GB
use length in your write as well as your read:
eg
Expand|Select|Wrap|Line Numbers
  1. fwrite(x, sizeof(x[0]), length, background);
  2.  
Yup,u heard TheMan

;)

Savage
May 23 '07 #16
niskin
109 100+
use length in your write as well as your read:
eg
Expand|Select|Wrap|Line Numbers
  1. fwrite(x, sizeof(x[0]), length, background);
  2.  
I have done this now and the image has still not been transferred. I opened the image in notepad to see if any more had been transferred than before. There are now 3 characters, before there was one.
May 23 '07 #17
Savage
1,764 Expert 1GB
I have done this now and the image has still not been transferred. I opened the image in notepad to see if any more had been transferred than before. There are now 3 characters, before there was one.
Maybe malloc doesn't allocate enough memory.

Try allocating memory for different data type.
May 23 '07 #18
niskin
109 100+
Maybe malloc doesn't allocate enough memory.

Try allocating memory for different data type.
Nope no change when allocating memory for char or float.
May 23 '07 #19
DeMan
1,806 1GB
Have you tried printing out the intermediate variables.....
Is the length you get from fseek correct?
What is the size of x?
Can you narrow down whether the read or write is causing the error?
May 23 '07 #20
Savage
1,764 Expert 1GB
Have you tried printing out the intermediate variables.....
Is the length you get from fseek correct?
What is the size of x?
Can you narrow down whether the read or write is causing the error?
The problem is in length.try printing it out.

Savage
May 23 '07 #21
Savage
1,764 Expert 1GB
The problem is in length.try printing it out.

Savage
Sorry for double post but I found the frustration maker(tm):

it was fseek:

right now ur fseek is called like:fseek(newpic,SEEK_END,0) ,but it should be

fseek(newpic,0,SEEK_END)

Savage
May 23 '07 #22
niskin
109 100+
Sorry for double post but I found the frustration maker(tm):

it was fseek:

right now ur fseek is called like:fseek(newpic,SEEK_END,0) ,but it should be

fseek(newpic,0,SEEK_END)

Savage
Right well the content of the file is now: Ä 0 h"0 (when opened in notepad)

It is not displaying any image.

Printing length and x does not work because the compiler is telling me that I'm trying to do an invalid conversion from int to char.
May 24 '07 #23
Savage
1,764 Expert 1GB
Right well the content of the file is now: Ä 0 h"0 (when opened in notepad)

It is not displaying any image.

Printing length and x does not work because the compiler is telling me that I'm trying to do an invalid conversion from int to char.
How did u tryed to print length?

It should be the same as the size of the file that u are coping

Savage
May 24 '07 #24
niskin
109 100+
How did u tryed to print length?

It should be the same as the size of the file that u are coping

Savage
I just did printf( length ).
May 24 '07 #25
Savage
1,764 Expert 1GB
I just did printf( length ).
Like:

printf("%d",length);

??

Savage
May 24 '07 #26
niskin
109 100+
Like:

printf("%d",length);

??

Savage
Lol I can't believe I missed that, sorry for being stupid. It printed: 101054

I have also just opened stbedes.jpg in notepad again. It appears that it has 4 characters but it seems to have a lot of spaces, and I would guess there are 101050 spaces because that would make up the rest of length and there are so many spaces that it is quite believable. Why is it coming up with 4 characters and 101050 spaces though?
May 24 '07 #27
DeMan
1,806 1GB
Incidently (though I don't think this is the cause of your problem),
you are allocating WAY more memory than you need.....
you don't need to multiply (length* sizeof(int)) = the length is already the total number of bytes
May 24 '07 #28
Savage
1,764 Expert 1GB
Incidently (though I don't think this is the cause of your problem),
you are allocating WAY more memory than you need.....
you don't need to multiply (length* sizeof(int)) = the length is already the total number of bytes
Yes that's true.

However when u remove sizeof(int) final file will have size of 0 bytes,or atleast that's what happens to me.


Savage
May 25 '07 #29
DeMan
1,806 1GB
you could use sizeof(char)....
May 25 '07 #30
Savage
1,764 Expert 1GB
you could use sizeof(char)....
Allready tryed that.

Same thing happens.

Savage
May 26 '07 #31
Before reading the file, you need to rewind it. The fseek command put you at the end of it, so no data is being read into your buffer. Use:

rewind(file_pointer)

where file_pointer refers to the file pointer of your input file, I believe it was "newpic".

thanks,
eric
Jun 5 '07 #32
Savage
1,764 Expert 1GB
Before reading the file, you need to rewind it. The fseek command put you at the end of it, so no data is being read into your buffer. Use:

rewind(file_pointer)

where file_pointer refers to the file pointer of your input file, I believe it was "newpic".

thanks,
eric
LOL,we all missed that.

Sharp eye eric..

Savage
Jun 5 '07 #33
niskin
109 100+
hate to say it but it's still not working :S
Jun 16 '07 #34
Savage
1,764 Expert 1GB
hate to say it but it's still not working :S
Can you shouw us your code?

And please can you tell us how it's not working?

Does it sitll copie a few characters or is it something else?

Savage
Jun 16 '07 #35
DeMan
1,806 1GB
fread (and I think fwrote also), return a value, this value represents the size read (or written).....
YOu might like to retrieve these values and print them to see whether one of these functions is causing the unexpected behaviour
Jun 16 '07 #36
Savage
1,764 Expert 1GB
fread (and I think fwrote also), return a value, this value represents the size read (or written).....
YOu might like to retrieve these values and print them to see whether one of these functions is causing the unexpected behaviour
Sorry Deman, but you are wrong, fread and fwrite returns number of elements readed/writen..

Still, OP can multiply with sizeof one element and that way discover unexpected behaviour, if there is one..

Savage
Jun 16 '07 #37
DeMan
1,806 1GB
fread and fwrite returns number of elements readed/writen..
Are you suggesting that number of elements does not constitute size (You'll notice units were never mentioned)?
Jun 16 '07 #38
Savage
1,764 Expert 1GB
Are you suggesting that number of elements does not constitute size (You'll notice units were never mentioned)?
It depandes on what is the size of the element user requested when he called fread or fwrite.If it is 1byte then you are correct,but if it is more bytes per element he will need to multiply returned value with size of single element readed/writen

Savage
Jun 17 '07 #39
DeMan
1,806 1GB
Granted, to get the size in bytes, number of elements needs to be mulktiplied by number of bytes in an element. But number of elements is still size (3 metres is still 3 metres even if it is 300 centimetres as well).

While printing the size in bytes may also be useful, I think it may also be helpful to print the size in number of elements, after all, you should probably consider data in its' rawest form if you want to find such peculiarities.

I appreciate that the size returned by these functions is not the size in bytes, however, I never suggested that it was, and feel my suggestion was worthwhile nonetheless.....
Jun 17 '07 #40
Savage
1,764 Expert 1GB
Granted, to get the size in bytes, number of elements needs to be mulktiplied by number of bytes in an element. But number of elements is still size (3 metres is still 3 metres even if it is 300 centimetres as well).

While printing the size in bytes may also be useful, I think it may also be helpful to print the size in number of elements, after all, you should probably consider data in its' rawest form if you want to find such peculiarities.

I appreciate that the size returned by these functions is not the size in bytes, however, I never suggested that it was, and feel my suggestion was worthwhile nonetheless.....
Sorry.

I thought that you are trying to tell that those functions returns size in bytes.

Savage
Jun 17 '07 #41

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: dave | last post by:
Hello there, I am at my wit's end ! I have used the following script succesfully to upload an image to my web space. But what I really want to be able to do is to update an existing record in a...
3
by: Roberto | last post by:
I have the following problem: I have the following form client side: <FORM.......> <FORM action="./WZUpload.asp" method="Post" enctype="multipart/form-data" WIDTH=100%> <INPUT Type="file"...
8
by: Brandon McCombs | last post by:
This may be the wrong group but I didn't see anything for VC++ so I'm trying here. I have a C++ book by Deitel and Deitel that says I can use fstream File("data.dat", ios::in | ios::out |...
8
by: Eric Lilja | last post by:
Hello, I had what I thought was normal text-file and I needed to locate a string matching a certain pattern in that file and, if found, replace that string. I thought this would be simple but I had...
2
by: Chucker | last post by:
Hi Community, I think I can store Binary Data in SQL Server but when I try to retrieve it, I always only get one byte. I think I stored my Binary Data in SQL Server in a Colum of Type Image....
3
by: BatthJeet | last post by:
Hi all ! Can we have some way to make a program in C-Language which opens an Image(.jpeg/.bmp ) file in binary mode like:- FILE *sourcefile; sourcefile=fopen("d:\\mypic.jpeg","rb"); Then...
1
by: bharathv6 | last post by:
i need to do is modify the image in memory like resizing the image in memory etc ... with out saving it disk as i have to return back the image with out saving it disk PIL supports the use of...
1
by: mohi | last post by:
hello every one , can anyone please help me ,,actually i want to load an image in c++ i.e i want to get the digital signature(a file which contains the pixel values of the image ) . thats all...
2
by: mobz | last post by:
Hi guys, My project includes capturing image using camera to a microcontroller.Then i send the picture overTCP/IP to be displayed on the web browser.. I have finished everything,but stuck...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.