@@ -48,6 +48,8 @@ public function __construct(string $bin_path = null, string $args = "--min 50 {I
48
48
}
49
49
50
50
/**
51
+ * Compress a specified JPEG file and write to a specified output path.
52
+ *
51
53
* @param string $input absolute path to input JPEG file
52
54
* @param string $output absolute path of output JPEG file
53
55
*
@@ -58,7 +60,7 @@ public function compress(string $input, string $output)
58
60
$ command = strtr (
59
61
"{$ this ->bin_path } {$ this ->args }" ,
60
62
[
61
- "{INPUT} " => escapeshellarg ($ input ),
63
+ "{INPUT} " => escapeshellarg ($ input ),
62
64
"{OUTPUT} " => escapeshellarg ($ output ),
63
65
]
64
66
);
@@ -67,4 +69,48 @@ public function compress(string $input, string $output)
67
69
68
70
$ process ->mustRun ();
69
71
}
72
+
73
+ /**
74
+ * Compress JPEG data from a given input stream and write the output data
75
+ * either to a given stream, or to a temporary stream, which will be returned.
76
+ *
77
+ * @param resource $input input stream resource
78
+ * @param resource|null $output optional output stream resource
79
+ *
80
+ * @return resource output stream resource (file pointer will be at the start of the stream)
81
+ *
82
+ * @throws ProcessFailedException on failure to execute the command-line tool
83
+ */
84
+ public function compressStream ($ input , &$ output = null )
85
+ {
86
+ $ command = strtr (
87
+ "{$ this ->bin_path } {$ this ->args }" ,
88
+ [
89
+ "{INPUT} " => "- " ,
90
+ "{OUTPUT} " => "- " ,
91
+ ]
92
+ );
93
+
94
+ $ process = new Process ($ command );
95
+
96
+ $ process ->setInput ($ input );
97
+
98
+ if ($ output === null ) {
99
+ $ output = fopen ("php://temp " , "w " );
100
+ }
101
+
102
+ $ status = $ process ->run (function ($ type , $ buffer ) use ($ output ) {
103
+ if ($ type === Process::OUT ) {
104
+ fwrite ($ output , $ buffer );
105
+ }
106
+ });
107
+
108
+ if ($ status !== 0 ) {
109
+ throw new ProcessFailedException ($ process );
110
+ }
111
+
112
+ rewind ($ output );
113
+
114
+ return $ output ;
115
+ }
70
116
}
0 commit comments