-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimation.cpp
84 lines (70 loc) · 2.1 KB
/
animation.cpp
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
/**
* @file animation.cpp
*
* Implementation of an animation class.
* @author Aria Buckles
* @date Fall 2011
*/
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <sys/stat.h>
#include "animation.h"
using namespace std;
template <typename T> inline string animation::to_string(const T &value)
{
stringstream ss;
ss << value;
return ss.str();
}
string animation::getString(int i, int padToSameLengthAs)
{
string istr = to_string(i);
string padstr = to_string(padToSameLengthAs);
return string(padstr.length() - istr.length(), '0') + istr;
}
bool animation::exists(const string &path)
{
// Try stat-ing it
struct stat st;
if (stat(path.c_str(), &st) != 0)
return false;
// Check for read permission
if ((st.st_mode & S_IRUSR) == 0)
return false;
// Check for correct file/directory nature
if (path[path.length() - 1] != '/')
return S_ISREG(st.st_mode);
// Otherwise we want a directory
if ((st.st_mode & S_IXUSR) == 0)
return false;
return S_ISDIR(st.st_mode);
}
void animation::addFrame(PNG const &img)
{
frames.push_back(img);
}
PNG animation::write(const std::string &filename)
{
if (frames.empty())
{
cout << "Animation Warning: No frames added!" << endl;
return PNG();
}
size_t filestart = filename.find_last_of("/");
filestart = (filestart == string::npos) ? 0 : filestart + 1;
size_t extstart = filename.find_last_of(".");
string name = filename.substr(filestart, extstart - filestart);
// Create the frames/ directory if it does not exist
if (!exists("frames/"))
mkdir("frames", 0700);
// Remove all previous frames from this image
system(("ls frames | grep '^" + name + ".*\\.png$' | xargs -I% rm -f frames/%").c_str());
// Generate Frames
for (size_t i = 0; i < frames.size(); i++)
frames[i].writeToFile(("frames/" + name + getString(i, frames.size()) + ".png").c_str());
// Combine frames
system(("convert frames/" + name + "*.png " + filename).c_str());
return frames[frames.size() - 1];
}