1
0

iconv.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. #include <memdraw.h>
  5. void
  6. usage(void)
  7. {
  8. fprint(2, "usage: iconv [-u] [-c chanstr] [file]\n");
  9. exits("usage");
  10. }
  11. void
  12. writeuncompressed(int fd, Memimage *m)
  13. {
  14. char chanstr[32];
  15. int bpl, y, j;
  16. uchar *buf;
  17. if(chantostr(chanstr, m->chan) == nil)
  18. sysfatal("can't convert channel descriptor: %r");
  19. fprint(fd, "%11s %11d %11d %11d %11d ",
  20. chanstr, m->r.min.x, m->r.min.y, m->r.max.x, m->r.max.y);
  21. bpl = bytesperline(m->r, m->depth);
  22. buf = malloc(bpl);
  23. if(buf == nil)
  24. sysfatal("malloc failed: %r");
  25. for(y=m->r.min.y; y<m->r.max.y; y++){
  26. j = unloadmemimage(m, Rect(m->r.min.x, y, m->r.max.x, y+1), buf, bpl);
  27. if(j != bpl)
  28. sysfatal("image unload failed: %r");
  29. if(write(fd, buf, bpl) != bpl)
  30. sysfatal("write failed: %r");
  31. }
  32. free(buf);
  33. }
  34. void
  35. main(int argc, char *argv[])
  36. {
  37. char *tostr, *file;
  38. int fd, uncompressed;
  39. ulong tochan;
  40. Memimage *m, *n;
  41. tostr = nil;
  42. uncompressed = 0;
  43. ARGBEGIN{
  44. case 'c':
  45. tostr = EARGF(usage());
  46. break;
  47. case 'u':
  48. uncompressed = 1;
  49. break;
  50. default:
  51. usage();
  52. }ARGEND
  53. memimageinit();
  54. file = "<stdin>";
  55. m = nil;
  56. switch(argc){
  57. case 0:
  58. m = readmemimage(0);
  59. break;
  60. case 1:
  61. file = argv[0];
  62. fd = open(file, OREAD);
  63. if(fd < 0)
  64. sysfatal("can't open %s: %r", file);
  65. m = readmemimage(fd);
  66. close(fd);
  67. break;
  68. default:
  69. usage();
  70. }
  71. if(m == nil)
  72. sysfatal("can't read %s: %r", file);
  73. if(tostr == nil)
  74. tochan = m->chan;
  75. else{
  76. tochan = strtochan(tostr);
  77. if(tochan == 0)
  78. sysfatal("bad channel descriptor '%s'", tostr);
  79. }
  80. n = allocmemimage(m->r, tochan);
  81. if(n == nil)
  82. sysfatal("can't allocate new image: %r");
  83. memimagedraw(n, n->r, m, m->r.min, nil, ZP, S);
  84. if(uncompressed)
  85. writeuncompressed(1, n);
  86. else
  87. writememimage(1, n);
  88. exits(nil);
  89. }